Sunday, January 23, 2011

SOLID Principle

In computer programming, SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Robert C. Martin in the early 2000s which stands for five basic patterns of object-oriented programming and design.




Single Responsibility Principle:
"There should never be more than one reason for a class to change."
If we have calculation logic and database logic and display logic all mixed up within one class it can be difficult to change one part without breaking others. Mixing responsibilities also makes the class harder to understand, harder to test, and increases the risk of duplicating logic in other parts of the design (decreases cohesion, functionality has no clear place to live).

Open Closed Principle:
"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
The idea is that we can use OO techniques like inheritance and composition to change (or extend) the behaviour of a class, without modifying the class itself.Following the OCP should make behaviour easier to change, and also help us avoid breaking existing behaviour while making changes.

Liskov Substitution Principle:
"Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it."
It states that, if S is a subtype of T, then objects of type T in a computer program may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.).

Interface Segregation Principle:
"Clients should not be forced to depend upon interfaces that they do not use." The ISP is about keeping interfaces (both interface, and abstract class types of interfaces) small and limited only to a very specific need (a single responsibility even :)). If you have a fat interface then you are imposing a huge implementation burden on anyone that wants to adhere to that contract.

Dependency Inversion Principle:
"A. High level modules should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions."

The DIP says that if a class has dependencies on other classes, it should rely on the dependencies' interfaces rather than their concrete types. The idea is that we isolate our class behind a boundary formed by the abstractions it depends upon. If all the details behind those abstractions change then our class is still safe. This helps keep coupling low and makes our design easier to change.

No comments: