SOLID Design Principles

In this article, i will try to summarize the SOLID principles of object-oriented design.
The concept of SOLID principles were described first by Robert C. Martin in his paper Design Principles and Design Patterns.
Later on, the SOLID acronym was introduced by Michael Feathers for these principles.

And here is the SOLID principles that we will outline in this article: 

  1. Single Responsibility
  2. Open-Closed
  3. Liskov Substitution
  4. Interface Segregation
  5. Dependency Inversion

1. Single Responsibility Principles (SRP)
The key points that this principle says:
- A class should have only one responsibility
- A class should only have one reason to change
- If the class belongs to domain model, it should represent only the relevant business entity.

Benefits:
- Testing: Less responsibility means fewer test cases
- Loose coupling: Less responsibility means fewer dependencies

2. Open-Closed Principle (OCP)
The key points that this principle says:
- Open for extension
A class should be written in a way that is open for implementing new requirements via extension.
- Closed for modification
A class should be written in a way that is closed for implementing new requirements via modification.
Modification for fixing bugs is not the implied case here since that is not the case for new requirements.
The motivation for not to modify the code is "do not change the working code".

An example for this principle to be understood is the painter class. 
Think that a painter class has a method named paint() which paints home. 
And a new requirement is to paint home and the garden if exists.
Then you should not modify the method with an if case of garden existence for painting since closed for modification.
Instead, as open for extension says, you should extend the painter class and override paint() to paint the garden also.


3. Liskov Substitution Principle (LSP)
The key points that this principle says:
- Subclasses must completely be replacable with their base types. 
- Meaning that; we should be able to pass a derived class wherever a base class is needed.
If we cannot, that means a violation of LSP exists.

4. Interface Segregation Principle (ISP)
The key points that this principle says:
- A class should not be forced to implement an interface containing methods that is not needed and not used by the implementation class.
- In other words, it tells us to make fine-grained interfaces that are client specific.
And that leads to smaller interfaces only concerned about the methods that are of interest instead of larger ones.

5. Dependency Inversion Principle (DIP)
The key points that this principle says:
- A class should depend on other abstract classes, not on concrete classes.
- This way ensures that high level modules not to depend on low-level modules, instead depend on abstractions.

References

Yorumlar

Popular

Dependency Injection In Java and CDI

Spring Components & Auto Scanning & Configuration

Servlet