Software Design Patterns

Design Principles

Design Principles:

Note that you can not follow these principles with 100% commitment to them. It would be impossible or at best, it would be a huge mess. You should strive to attain these principles, and when you are breaking one of these, you should think twice about whether or not you should. As you become used to programming with these principles in mind, it will get less confusing.

As an example, take Principle #2, "Program to an interface, not an implementation". This can be interpreted a few ways. For now, lets interpret it to mean you should program to a type (inteface), not to a concrete class of some subtype of that type. In reality, it wouldn't be very useful to have the subtype if you can't use it at some point. In general you should deal with the object's type in all cases where you don't specifically need to deal with the concrete class.

  • #1 - Identify the aspects of your application that vary and separate them from what stays the same.
  • #2 - Program to an interface, not an implementation.
  • #3 - Favor composition over inheritance (has-a instead of is-a).
  • #4 - Strive for loosely coupled designs between objects that interact.
  • #5 - Classes should be open for extension , but for closed for modification.
    (The Open-Closed Principle). Sounds like a contradiction, but you can use patterns to design your code so that when things need to change, you can extend the class instead of modifying the existing classes.
  • #6 - Depend upon abstractions. Do not depend on concrete classes.
  • #7 - Principle of Least Knowlege - talk only to your immediate friends.
    Avoid having your class interact with many classes all over your application which would cause tight coupling, which would then cause changes in one part of your app to cascade to other parts. This would a fragile system, hard to maintain.
  • #8 - The Hollywood Principle - Don't call us, we'll call you.
    This means high level components can call low level components but not the other way around. For instance, if you have a UI Layer, BusinessLayer, DataAccess Layer, Database (highest to lowest level), the high level objects can call the low level (Business Layer can call DataAccess Layer, but not vice-versa). Adhering to this rule prevents circular references that cause maintanence nightmares.
    In the case of objects, this means clients should call communicate with the base type. If you have the an 'automobile' type, and a 'car' and 'truck' class that derive from 'automobile' then the client should talk to 'automobile' and then polymorphism take care of executing the method of the derived class (car or truck). Similar to #2.
  • #9 - A class should have only one reason to change. This principle guides us to assign each responsibility to one class and only one class.

0 Comments