Tuesday, January 18, 2011

OO Principles

Encapsulate that varies
Place functionality that may change into a separate class that can be utilized by other classes.

Favor composition over inheritance
Composition facilitates better reuse of code, results in less code duplication, and has fewer side-effects than inheritance. Instead of defining a common behavior in the base class, encapsulate that behavior in a separate class that can be utilized by classes in the inheritance hierarchy through composition.

Program to interfaces, not implementations
Encapsulate functionality into a class that implements an interface. The user of the functionality is coded against the interface of the class, not its concrete implementation.

Loose Coupling
When two or more classes or family of classes need to collaborate, share as little implementation details of classes with each other as possible. There are several techniques to achieve loose coupling. For example, program to interfaces instead of concrete class implementations. This allows us to swap class implementations without having to change the code that is written against an interface. When applicable, Observer Pattern is another way to achieve loose coupling where the Subject knows very little about its Observers and begins and ends its relationship with its Observers at runtime.

Open-Closed Principle
This principle advocates a design that is extensible without having to make modifications to existing code. Decorator Pattern illustrates the application of this principle very well.