Pages

Saturday, April 14, 2012

Design Principle

1. Separating what changes from what stays the same
   - Take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don't.
Example:  Strategy pattern

2. Program to an interface, not an implementation.
    "program  to an interface" really means program to a supertype (usually an abstract class or interface)." The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn't lock into the code.

3. Favor composition over inheritance
Creating systems using composition gives you a lot more flexibility. Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime  as long as the object you are composing with implements the correct behaior interface.

4. Open for Extension, Close for modification
The goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code.

Be careful when choosing the areas of code that need to be extended; applying the Open-Closed Principle EVERYWHERE is wasteful, unnecessary, and can lead to complex, hard to understand code.

example: decorator pattern

5. Dependency Inversion Principle
    Depend upon abstractions. Do not depend upon concrete classes.
    It suggests that the high-level components should not depend on low-level components; rather, they should both depend on abstractions. A "high-level" component is a class with behavior defined in terms of other, "low level" components. For example, PizzaStore is a high-level component because its behavior is defined in terms of pizzas - it creates all the different pizza objects, prepares, bakes, cuts and boxes them, while the pizzas it uses are low-level components.

example: factory pattern

a few guidelines to help follow the principle
  • No variable should hold a reference to a concrete class.  
  • - If you use new, you'll be holding a reference to a concrete class. Use a factory to get around that.
  • No class should derive from a concrete class. 
  • - If you derive from a concrete class, you're depending on a concrete class. Derive from an abstraction, like an interface or an abstract class.
  • No method should override an implemented method of any of its bass classes.
  • - If you override an implemented method, then your base class wasn't really an abstraction to start with. Those methods implemented in the base class are meant to be shared by all your subclasses.







No comments:

Post a Comment