Showing posts with label Design Principles. Show all posts
Showing posts with label Design Principles. Show all posts

June 12, 2009

Good Design Thoughts


1. Encapsulate what varies --> identify the sections that vary and separate them from what stays the same
2. Favour composition over inheritance --> use "has-a" it is better than "is-a"
3. program to interface not implementations
4. Strive for loosely coupled designs between objects that interact (think mediator/observer)
5. Classes should be open for extension but closed for modification (think decorator pattern wrap around to extend)
6. Depend on abstracts not on concrete classes (an example would be factory method)
7. only talk to your friends (avoid having large number of classes coupled together)
8. dont call us, we will call you (template method - let superclass re-direct to subclasses)
9. A class should have only 1 reason to change

Inheritance vs Aggregation vs Composition


Inheritance - "Is A" Strongest Relationship

We depend on the functionalities of a Super Class

Aggregation - "Has A / Is Part Of" - Weaker Relationship

As shown in the example Aggregation occurs when the part of outlives the whole. e.g the listener instance could be alive even after WebServer instance is garbage collected


Aggregation Example ("has a"):



Composition - "Uses A" - Stronger Relationship

In a composition relationship the listener instance lifespan lasts till the WebServer instance is garbage collected.


Composition Example ("uses a"):