Skip to content

Instantly share code, notes, and snippets.

@ennisa-ire
Last active December 20, 2018 13:21
Show Gist options
  • Save ennisa-ire/333882be4976f6bd263c3b1b0797bb83 to your computer and use it in GitHub Desktop.
Save ennisa-ire/333882be4976f6bd263c3b1b0797bb83 to your computer and use it in GitHub Desktop.
00 - IoT Tech Design Corner

Design Principles

UML

Design Patterns

Creational

Structural


When we think of design, one thinks of famous architects and engineers, indeed they are designers, and not to have design at the fore front of your thinking is folley. Design has many aspects to it, it is primarly about intent though, and the realization of a solution to a long standing problem. When we think of design we think of design patterns, and principles of design, both of which should guide you through to your solution. Good luck and think out of the box!

Title Design Corner 101
Description The purpose of this information is to guide your through the process of design your own SW projects, without repeating problems that good design has already captured
Created By @Anthony Ennis
Date Created 01.01.2018
Maintained By IoT Tech

Note

  • The following principles are not specific to a language binding.

Dont Repeat Yourself

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system

Claims (Why We Use It)

If you adhere to DRY,

  • A modification of a dry unit of knowlege will not result in any logically unrelated elements needing a change either. They are isolated from change!!!
  • On the otherside of this, a modification of an element that is logically related, will result in a change to that element, but that change will be predictable, and uniform in nature, therefore in sync.
  • Is to eliminate redundancy

How

DRY is not just for code, it can be applied to Test plans, Schemas, and even build systems.

Eg : Using a framework!!!

  • Consider a web application, especially a multi-tier one, and consider the case were the developer is charged with updating a html form with a comment field. For sure the word will be repeated in the HTML code, a SQL query, and documentation. The point is there are many points of change. If one was to employ a framework, or template enginer, then the points of change are limited to the single unit of knowlege ie template engine, framework.
  • Consider restassured framework you build at AIB, this is an example of an expert capturing knowlege in one place, so that error, and duplication are managed.

Ponder : Is this why frameworks are so important to your project today. Check out our tech stack for a list of recommendations!!!

Eg: Methods
In you java code, encapsulate you code into a method!!! The class that encloses this method, can be consumed by clients as needed.

Eg: Code Generators
Consider MicroSofts IDE, and ask it to generate an new MFC project, it will does just that, by producing 2000 lines of code for you :)

Code Smells

  • WET is the collolary to DRY.

References

UML

You cannot have a conversation about design, without having a conversation about design notation UML, and object orientated analsysis, and design. UML is the prevailing notation used by SW programmers and BAs to model the problem domain. UML offers you groups of diagrams pretaining to

  • Objects identification and messaging.
  • Classification of objects into groups called classes
  • Sequence and timing diagrams relationing to object interaction.
  • Activity diagrams
  • State transition diagrams.

So lets get into it!!! and start with the problem!!!

Problem Domain

Objects

  • Objects encapsulate data, only the public interface operations are available to a client.
  • Changing an objects attributes, or reference values and you are changing its state. Change an objects state, could result in a change to the behaviour of the object.
  • There are there types of objects to consider
  1. Entity : These classes map to you use cases, they are something know as application, or business objects. They also have data associated with them!! They are used by BAs to model the system.
  2. Boundary : Take input from the actor, and optional return results back to the actor. Look to the use case diagram to determine boundarys
  3. Controller : handles the execution sequence, captures the real world procedures we need to keep track of!!! The controller orchastes/mediates between entity and boundary classes. More over the controller recieves command from the boundary!! The controller implements one or more of your usecase!!!
  • No matter how simple the system you will always have at least one boundary/control object. In some cases were simple is really simple, one class would serve as boundary, controller, where the controller is but an operation.
  • The EBC pattern is a simpler representation of a MVC pattern.

Finding objects!!

  • look to the flow of events in your use cases
  • do text analysis noun-verb, nouns will represent objects, and verbs, operations. This is know as Abbots technique.

Example for using the Technique

  • The customer enters the store to buy a toy.
  • It has to be a toy that his daughter likes and it must cost less than 50 Euro.
  • He tries a videogame, which uses a data glove and a head-mounted display. He likes it.
  • An assistant helps him.
  • The suitability of the game depends on the age of the child.
  • His daughter is only 3 years old.
  • The assistant recommends another type of toy, namely the boardgame “Monopoly".
Example Part of Speech Model Component
"Monopoly” Proper noun object
Toy Improper noun class
Buy,recommend Doing verb operation
is-a being verb inheritance
has an having verb aggregation
must be modal verb constraint

Ref : https://www1.in.tum.de/lehrstuhl_1/files/teaching/ws0607/Software%20Engineering%20I/L6_ObjectModeling.pdf

Classes

The idea for a class notation came into affect because of a need to classify groups of objects together!!! This grouping is a skill in its self, and will first lead to the classification name. Here are some pointers to classification.

Finding classes

Generating a Class Diagram from Flow of Events

Ref : https://www1.in.tum.de/lehrstuhl_1/files/teaching/ws0607/Software%20Engineering%20I/L6_ObjectModeling.pdf

Concreate Classes

  • Look to the objects that exist in the problem domain, you will see nouns i.e. names of persons, places or things. The Class names are usually that of nouns, but can identify processes too.
  • A class will encapsulate the essence of the objects behaviour over a time period - observe your objects well to understand their full behaviour. The essence is notated via properties and operations which are specified in the class.
  • A class can be instantiated.
  • A class has methods, which is the code, which is the meat behind the operations of the class.

Abstract Classes

  • The A-Class is an interest concept, remember classes are there to notate the object world.
  • Abstract means empty - not reall, needs to be implementated!!!
  • Consider the world of Pizza, you got a margertta, your peroni, your hawanina, and so on, they differ only with toppings. The base, and maybe the sauce too, is the same for our purposes. It makes sense to define the properties, and operations around a the family pizza objects into an abstract class, so that when a new pizza topping is invented, its still behaves like the old ones!!!
  • Sometimes we want to boiler plate code that we know is common to all descendants that will make up the grouping.
  • Note abstract classses are never instaniated!! they are used by overwriting there operations with method informaiton that is correct for they type of pizza!!! If you try to instantiate an abstract class you will get a runtime error.
  • An abstract class contains properties and operations just like a real aka concrete class!!!.
  • An abstract class will have abstract methods

Git Hub Source Code :

Relationships

  • Association is a relationship where all objects have their own lifecycle and there is no owner.
    Eg :
    Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
  • Aggregation is a specialised form of Association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object.
    Eg:
    Let's take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department, the teacher object will not be destroyed. We can think about it as a “has-a” relationship.
  • Composition is again specialised form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have its lifecycle and if parent object is deleted, all child objects will also be deleted.
    Eg:
    Let's take again an example of relationship between House and Rooms. House can contain multiple rooms - there is no independent life of room and any room can not belong to two different houses. If we delete the house - room will automatically be deleted.
    Let's take another example relationship between Questions and Options. Single questions can have multiple options and option can not belong to multiple questions. If we delete the questions, options will automatically be deleted.

Interface

Eg : A Menu The items on the menu could be listed as follows

Soup Of the Day
Steak n Chips
Apple Tart

A small menu indeed. The menu is an interface, it offers behaviour to the client. If the client has questions around the interface, he will as the waiter.

Consider the situation were you have multiple menus, as foods menu, a desserts menu, and a wine menu. This is an example of a restaurant, following the principle of interface segratation

Immutability

As a coder, you should ensure that you class is not changed easyly, but this i mean that the flds of the class, should be set to private, and setters are not used, an object STATE should be set at construction. If not side effects are possible

  • try not to use setters!!
  • use constructors to set state!!

If you objects are mutable, then you will have have a thread safe program experience.

Polymorphism

Extending Code

Method Overwriting

Method Overloading.

Template Methods

derived classes, are sub classes!!!

Course Notes In our conversations on desing patterns we will use terms like

  • Director
  • Client
  • Delegator
  • x
  • x
  • Calling, calling framework
  • Messaging
  • Signalling

When trying to under a UML diagram, you need to ask question around the relationships, why they exist, and reference the objecst that the class if ultimately referenceing...

Diagrams

Sequence Diagrams

  • This diagram, has handlers, and drivers.
  • It expresses the events flow listed in a use case, or part of a use case.
  • The Driver is the controller.

Note : The sequence diag. is the use case narrative, run through it, again and again, makeing sure both are in sync

State Diagrams

  • All objects have state, but are the worthy of a state diagram, yes, but only if they have at least three states, and are important to the business.
  • A decision point will lead to a new state
  • Use the state design pattern to enforce state in a classs.

Analysis Q. What is the difference between an Interface and an Abstract class?

  1. You cannot instaniate an abstract class.

References

  1. http://www.cs.sjsu.edu/~pearce/modules/lectures/ooa/analysis/ecb.htm
  2. http://www.cs.sjsu.edu/~pearce/modules/lectures/ooa/analysis/browser/analysisModel.htm
  3. http://www.cs.sjsu.edu/~pearce/modules/lectures/ooa/analysis/atm/analysisModel.htm

Dependency Management

  • Be carefull, keep your dependencies under control!!!!
  • Dependencies can be your downnfall!!!
  • Choose your dependants well, are they right for you

App Servers
Test Frameworks
etc

  • Dependency show be a one way street, you depend on them?

🔴 Single Responsibility

Image of Yaktocat

Claims (Why We Use It)

  • Problems it addresses.....

Whats

  • Scream Points
  1. Dependency is owned by someone else, and you need it at a certain, time, and in a certain manner.
  • Description
  1. if you were to look at a class, what should jump out is!!! it should scream class.
  2. It should do one thing, or put another way, have one reason to change.

Note

  • The word change is important to understand, we are talking about a change in value to a property, therefore its state.
Eg: 
// I am a car, I have the following Responsibilities, simply reach out to me, and I will do the following, am I over loaded, will i become stressed ?

1. starts the car
2. stops the car
3.
4.
5.
6. more than six things to do!!!! 


Class Car {
    starts(), stops(), right(), left(), forward();
}

Q. Why whould you change this class ? I see an Engine!!

Class Engine {
    starts()
}

I see breaks!!!
Class Break {
    stops()
}

I see a Steering column

Class SteeringColumn {
    right();
    left();
}


So looking at your car class now, do you see a reason to change it behaviour or properties? 
* Its responsibliity is to hold the components together!!!!
* It should only change if, new parts are added to the car!!!

Class Car {
    Cost cost;
    Model model;
    ArrayList<Parts> parts;

    setCost(Cost cost) {
        // if not  null - else throug paramter exception!!!
    };
    setModel(Model model) {
        // if not  null - else throug paramter exception!!!
    };

    addPart(Part part) {
        // if not  null - else throug paramter exception!!!
        parts.add(part);
    };
}

So the car class looks thought its nothing more than a container. 
If you class is now SRP safe, it should not change over time!!! this will mean all following unit tests would be secure. 
Associations are fit for purpose


New look at the following bird class!!!
Class Bird {
    fly(), sing(), eat(), waddle();
}


Some examples of responsibilities to consider that may need to be separated include:

Persistence
Validation
Notification
Error Handling
Logging
Class Selection / Instantiation
Formatting
Parsing
Mapping

Hows

Heres what you need to do

Facts

Related Topics

🔴 Open/Closed

OpenClosedPrinciple

Claims (Why We Use It)

  • If you adhere to it, then if you have switch statment in the code, then all cases listed are exhaustive.
  • That increase productivity?

Whats

  • Scream Points
  1. Open means you can extend its behaviour via inheritance and overriding behaviours, and compositional design via strategy pattern (http://deviq.com/strategy-design-pattern/)
  2. Closed means that class is left with completed behaviour, and set of properties.

Eg : Real Worlds

  1. Smart phone, is open for extentesion, via its app store
  2. Consider a class, that writes to a file, if the name of the file is hardcoded, then this class would have to be changed if the requirement changed :(

How

You can extend methods, and classes

Eg : Method Overloading

Eg : Extending Classes.

Eg : Compositional Design.

  • This principle applies to modules, and classes.

Relates To

  • Strategic Design Pattern.

🔴 Liskov Substituion

Duck Or Not

Claims (Why We Use It)

  • A swapability exists between parent and child without affecting expected behaviour.

Whats

  • The derived class should have an implementation that does break the "sentiment" of the base classes implementation for the same behaviour, when the derived class is swapped out for the base class.

Eg : Real World

  • Consider an Animal class with a method makeNoise(), if one was to extend this with a Cat class, if would be reasonable for the cat class to implement makeNosie() as a meow!!!

Hows

Heres what you need to do

Code Smell

A common code smell that frequently indicates an LSP violation is the presence of type checking code within a code block that should be polymorphic. For instance, if you have a foreach loop over a collection of objects of type Foo, and within this loop there is a check to see if Foo is in fact Bar (subtype of Foo), then this is almost certainly an LSP violation. If instead you ensure Bar is in all ways substitutable for Foo, there should be no need to include such a check.

Facts

Related Topics

  • Open/Close Principle

Further Reading

🔴 Interface Segragation

ISP

Intro

Todays installment of design principles today will demonstrate the importance of......segragation, more over how important it is to de-clutter your interface definations!!!

Claims (Why We Use It)

  • Will make it easier ....
  1. for clients of the interface to implement the methods that make up the interface.
  2. It also mean that clients will not have to implement interfaces that are not relevent to the clients needs!!
  3. Clients will not have to recompile there code as inteface methods are likley to change, give the unnessacary amount of method signatures existing in the interface.
  4. Are recompile of code will result in a new deployment!!!

What

Lets decompose the elements, and look closer at the problem.......

  • What is a interface? An interface is used by classes, and even other interfaces. In other words an interface has clients, including its own fellow interfaces. You can imagine an interface as a service then, which will have clients, as such the presentation of the interface is important, you do not want to present to much or too little, put another way, you interface should not be a monster, and should be in keeping with the sentiment, of the interface name!

  • What are we trying to segragate and why? We want to separate out methods in the interface spec, are not in keeping with the name of the inteface. That is not to say we will purge these methods, what is means, is that such methods will be placed into new interfaces which will better represent them.

Eg : Menu Time!!! consider the following big menu, which is listed as follows

-Brunos Bistro!!!-

Soup Of the Day
Steak n Chips

Apple Tart
Ice Cream

White Wine
Red Wine

The menu is an interface, it offers behaviour(s) to the client. If the client has questions around the interface, he will as the waiter.

Consider the situation were more items are added to the menu, and you client is a T-Totaller, it makes sense to have multiple menus, foods menu, desserts menu, and a wine menu. This is an example of a restaurant, following the principle of interface segratation. Get it?

As an aside the soup of the day option is interesting, why?

  1. if forces the client to ask the waiter what it is!!!
  2. The owners of the interface aka foods menu, dont have to rewrite it every day, a good interface!!! furthermore the client wont have to recompile theire code :), but will have to still ask the waiter.

Hows

How do you implement the principle of interface segragation in Java? To do this you would look to your project and look for fat interfaces, decompose these interfaces into smaller focused ones. Then depending on the clients needs, the client could implement one or more of the interfaces as needed.

public Interface MeDontLike {
  bool Login(string username, string password);
  void Logout(string username);
  Guid Register(string username, string password, string email);
  void ForgotPassword(string username);
}

Better solution.....

public Interface Authentication {
  bool Login(string username, string password);
  void Logout(string username);
  void ForgotPassword(string username);
}

public Interface Membership {
  Guid Register(string username, string password, string email);
  void ForgotPassword(string username);
}

A client could then consume both interfaces if needed

public class Login implements Authentication, Membership

Note A code smell would be an interface that contains many operations, monolithic in nature, operations that are contradicator to the name of the interface, a so called FAT interface.

Demo Time

What you need

http://localhost:5000/env-bb-qa2/edit

References

🔴 Dependency Inversion

Whats

  • DI simply put is where any dependencies objects that are new-ed up in the class are removed, instead the objects are passed into the class by handler class

Claims (Why We Use It)

Its claims are as follows

  1. Makes Classes easier to unit test
  2. Classes are easier to change
  3. Classes are .......

Hows

  • DI can take place of following levels
  1. Constructor
  2. Setter
  3. Interface.

It would seem the constructor mode is more desirable.

  • DI is supported by many frameworks
  1. google has given us juice, and more recently dagger.
  2. Cucumber has given us pico container
  3. Spring.....
  • In DI parlance, one talks of the client, and the service(s), the client is the class that depends on the services. These are the services that were once new-ed up in the class, but no longer.
  • DI does not need a DI framework, you can assemble the dependency yourself via main(), you also can implementat your very own DI if you know how!!!

Related Topics

  • Dependency Graphs
  • Client/Server relationships
  • Coupling/Decoupling.

Facts

  • DI is a design pattern!!!
  • Is part of a boarder topic called Control Of Inversion
  • DI depiction is ofened visualise in Depency graphs.

Further Reading

https://dzone.com/articles/the-solid-principles-in-real-life

🔴 Builder

Builder

Intro

In todays installment of design patterns we will demonstrate the importance of......been able to initialize an object in such a way that it fits the client needs!!!

Intent

Is to find a solution to the telescopic constructor anit-pattern. This is were a constructors arguments list is at such a size, that the number of constructors needed is not practical.

Claims (Why We Use It)

  • The client doesnt need to know each value a property needs to have, as defaults will be used when the client doest set it!!
  • The client can initialise a class in such a way, that if not all the options are needed to be fufill, the run time state would be valid
  • To allow a class to create different represenations of itself, via the same construction process....as an aside this shares features of the state design pattern?

Whats

The builder is an agent that will take care of the initiazing of the class with many parameters in it.

How

  • The work of initializing the object is removed from the object itself. It is given to a helper object, call a Builder.
  • The builder contains the parameters the class once had. Each of the paramters are initialized via a setter. Each setter will support the fluent design pattern.
  • The final method returned by the builder class will be the desired object, with all values previously set.

References

Release File

''' // Read Existing Tag node ("linux") {

sh ("ls -lrt .") def releaseFile="production-releases.md" def readContent = readFile "$WORKSPACE/$releaseFile"

writeFile file: releaseFile, text: readContent+"\r\nversion := 1.0.${env.BUILD_ID}" archive '**/*' def tag=""

tag+="lint." tag+="ut." tag+="ux"

if ( tag.toString().contains("lint.ut.ux") ) { echo "INF: Production Release Candiate Created" tag = "production"
} else { echo "INF: Release Candiate Created"

} def result switch(tag) { case "develop": result = "dev" break case ["master", "support/${tag}".toString()]: result = "list" break case "support/${tag}": result = "sup" break default: result = "def" break } echo "${result}"

} '''

Hudson Model

script { // some block def result = manager.build.testResultAction.result def total = result.totalCount def failed = result.failCount

manager.addShortText(failed + " / " + total + " failed")

}

Mini Cucumber Report Utility

node ("linux") {

git url: 'https://github.aig.net/commercial-it-global-delivery/cucumberReportGenerator-5416.git'
mvn = tool name: 'M3', type: 'maven'
sh("ls -lrt")
sh "${mvn}/bin/mvn clean package"  
archive "*/**"
cucumber fileIncludePattern: 'src/test/resources/*.json', sortingMethod: 'ALPHABETICAL'

}

Parrellel Test

node ("linux") {

parallel (
    
    "curl#1" : {
        sh "date"
    	sh "curl -X GET http://global.artifactory.devops.aig.net/artifactory/list/ts-paas-pcf-prod-local/buildpacks/java/java-buildpack-offline-v4.9.zip -o bp.zip"
        sh "date"
        sh "rm bp.zip"
    }

, "curl#2" : { sh "date" sh "curl -X GET http://global.artifactory.devops.aig.net/artifactory/list/ts-paas-pcf-prod-local/buildpacks/java/java-buildpack-offline-v4.9.zip -o bp2.zip" sh "date" sh "rm bp2.zip" }

)

}

Seq Test

node ("linux") {

sh "date"
sh "curl -X GET http://global.artifactory.devops.aig.net/artifactory/list/ts-paas-pcf-prod-local/buildpacks/java/java-buildpack-offline-v4.9.zip -o bp.zip"
sh "date"
sh "rm bp.zip"

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment