SOLID principles

Revision as of 04:18, 4 June 2018 by Rasimsen (talk | contribs) (Created page with " The SOLID principles acronym was introduced by Michael Feathers for five principles that were defined by Robert C. Martin in the early 2000s. We should have a low coupling,...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


The SOLID principles acronym was introduced by Michael Feathers for five principles that were defined by Robert C. Martin in the early 2000s.

We should have a low coupling, high cohesion and strong encapsulation, which is something that the SOLID principles help us obtain. The idea is that, by applying those principles together, you are able to write better quality code that is robust. The system created becomes easy to maintain, to reuse and to extend over time. Basically, SOLID principles help software developers to achieve scalability and avoid that your code breaks every time you face a change.

S – Single-Responsibility Principle.

“There should be never more than one reason for a class to change.”

As you can see, this principle states that an object/class should only have one responsibility and that it should be completely encapsulated by the class. Here, when we talk about a responsibility, we mean a reason to change. This principle will lead to a stronger cohesion in the class and looser coupling between dependency classes, better readability, and code with lower complexity.

It is much more difficult to understand and edit a class when it has various responsibilities. So if we have more than one reason to change, the functionality will be split into two classes and each will handle its own responsibility.

We care about separating the functionalities because each responsibility is an access of change. When a class has more than a single responsibility, those responsibilities become coupled and this coupling can lead to a fragile code base that is difficult to refactor when your requirements emerge.

O – Open-Closed Principle.

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

Here, the idea is that an entity allows its behavior to be extended but never by modifying its source code. Any class (or whatever you write) should be written in such a way that it can be used as is. It can be extended if need be, but it can never be modified. You can consider this when you are writing your classes. Use the class in any way you need, but modifying its behavior comes by adding new code, never by modifying the old. The same principle can be applied to modules, packages, and libraries.

By applying the open-closed principle you will get a loose coupling, you will improve readability and, finally, you will be reducing the risk of breaking existing functionality.

L – Liskov Substitution Principle.

“Subtypes must be substitutable for their base types.”


I – Interface Segregation Principle.

D – Dependency Inversion Principle.