Friday, January 25, 2019

SOLID Principles (part 1)

SOLID, an acronym for five design principles, was first introduced by Michael Feathers. The principles are a subset of many principles promoted by Robert C. Martin (“Uncle Bob”).

SOLID Acronym
  • Single Responsibility Principle (SRP)
  • Open closed Principle (OSP)
  • Liskov substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

1. Single Responsibility Principle: “A class should have one, and only one, reason to change.”

Every module/class should have the responsibility over a single portion of the functionality provided by the overall system/software, and that responsibility should be entirely encapsulated by the class.

When new requirements will be introduced, the code has to undergo some changes, meaning that the classes have to be modified. The more responsibilities a class will have, the more change requests it will get. And it will be harder to implement those changes.

In Single Responsibility Principle, each class and module should focus on a single task at a time. Everything in the class should be related to that single purpose. There can be many members in the class as long as they related to the single responsibility.

One example of SRP can be found here.

2. Open/Closed Principle: “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

There are many ways we can apply OCP. The easiest way to apply OCP is to inherit the original class and implement the new functionality on that new derived class.

But, inheritance can introduce tight coupling if the subclasses depend on implementation details of their parent class. That’s why Robert C. Martin and others redefined OCP to the Polymorphic OCP. It uses interfaces instead of superclasses to allow different implementations which you can easily substitute without changing the code that uses them. The interfaces are closed for modifications, and you can provide new implementations to extend the functionality of your software.

One example of OCP can be found here .


References:

No comments:

Post a Comment