SOLID Principles

Minindu Kothalawala
3 min readApr 11, 2021

Few of the most important principles in “Better Coding

S Single responsible principle

O → Open/Close principle

L → Liskov substitution principle

I → Interface segregation principle

D → Dependency inversion principle

Single Responsible Principle

A class should have one responsibility. Furthermore, it should have one reason to change.

  • This principle not mean, that classes should only have an one method or property.
  • Sometimes there can be few methods but, only one responsibility. Same as some times can be only one method but several responsibility.

Benefits:

  1. Testing : A class with one responsibility, will have far fewer test cases.
  2. Lower coupling : Less functionality in a single class will have fewer dependencies.
  3. Organization : Smaller, well organized classes are easier to search than monolithic ones.

Open / Close Principle

Classes should be open for extension but closed for modifications.

Open for Extensions:

Should design classes so that new functionalities can be added as new requirements are generated.

Closed for Modifications:

Once developed a class should never modify it, except to correct bugs.

Benefits:

  1. Limits to need change source code once it has been written, tested and debugged.
  2. Reduce the risk of introducing new bugs to existing code.
  3. Reduce coupling and increased flexibility.

Liskov substitution principle

If a subclass does something that the client of the superclass does not expect, then this is in violate Liskov substitution principle.

  • Applies to inheritance hierarchy.
  • All subclasses must, therefore operate in the same manner as their base classes.
  • The specific functionality of the sub class may be different but must conform to the expected behavior of the base class.
  • If violate this principle, it works okay during development but bows up in production.

Benefits:

  1. Code become clear.
  2. Reduce the complexity and much easier to debugging.

Interface segregation principle

Larger interface should be split into smaller once. By doing so, we can ensure that implementing classes only need to be concerned about the methods that are of interest to them.

Benefits:

  1. Minimize dependencies on unused members.
  2. Reducing coupling.
  3. smaller interfaces are easier to implement.
  4. improve flexibility and possibility of reuse.

Dependency inversion principle

State that high-level modules should not depend upon low-level modules. they should depend on abstraction.

Abstraction should not depend on details, details should depend upon abstraction.

  • The idea is that we isolated our class behind a boundary formed by the abstraction. It depends on.
  • If all the details behind those abstraction change, then one class is still safe.

Benefits:

  1. Keep coupling low.
  2. Make design easier to change.

--

--