it states that the software entities (classes, modules, functions,..etc.) should be open for extension but closed for modification.
in this principle we want to be able to add a new behavior ‘open to extension’. without the need to change our source or binary code ‘closed to modification’. or in other words we should strive to write code that doesn’t have to be changed every time the requirements change.
huh! change behavior without changing the code. !!
Yes we can achieve this by relying on abstraction (Interfaces, Abstract Base Classes) because there is no limit to number of different ways we can implement that abstraction .
An Example :
Suppose that there is a class called Rectangle that has a width and height properties within it.
Every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
In this principle the class should be only responsible for one thing or one task to do. responsible here means a reason to change, there must be never more than one reason to change your code ‘class’.
The more responsibilities we have the more likelihood of change and the more changes affects the more errors will be introduced.
In the SRP we want to strive for low coupling but high cohesion
cohesion: Is the degree to which the elements of a module or class belong together.
coupling: Is the degree to which each program module or class relies on each one of the other modules.
So Coupling talks about the inter-dependencies between the various modules while cohesion describes how related functions within a module are.
S.O.L.I.D is an acronym for the five basic principles of object-oriented programming and design identified by Robert C. Martin (Uncle Bob) in the early 2000s. The principles when applied together intend to make your code easy to maintain and extendable.
1- Single Responsibility Principle:
every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
2- The Open-Closed Principle:
the class should be open for extension but closed for modification .
3- Liskov substitution Principle:
it states that derived class should be substitutable for their base class. which means that if I substitute the derived class to its base class every thing should work with the same behavior and give me the same output .
4- Interface Segregation Principle:
it states that clients should not be forced to depend on methods they do not use . Don’t build fat Interfaces, only small cohesive interfaces to be matched with the client needs.
5- Dependency inversion Principle:
it states that high-level classes should not depend on low-level class. both should depend on abstraction. and abstraction should not depend on details but details should depend on abstraction. which means that you should depend on a concept not on an implementation.