DEV Community

Repana Reddy Sekhar
Repana Reddy Sekhar

Posted on

SOLID Principles

The SOLID principles are a set of five design principles in software development intended to make software designs more understandable, flexible, and maintainable.
These principles were introduced by Robert C. Martin (also known as Uncle Bob) to guide developers in creating better software architecture.

We will look each of these principles one by one:

Single Responsibility Principle (SRP)

It states that

A class should have one and only one reason to change

Example:

Image description

If we carefully observe in the above Employee class, we are doing two things i.e storing employee and calculating pay which defies SRF.

The Solution for the above problem is just create two classes like below:

Image description

Open Closed Principle (OCP):

It states that 




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

Example:
Let us consider below class to calculate penal fee based on lender:

Image description

Suppose if we want to add another lender, we need to modify this class which is not best practice and defies OCP.

Solution for the above problem is:

Image description

Liskov Substitution Principle (LSP)

It states that 




Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program

In other words,
Inheritance hierarchies such that derived classes must be completely substitutable for their base classes

Example:

Image description

In the above code, we have seen it clearly violates LSP.

Solution for the above problem is:

Image description

Interface Segregation Principle

It states that 




Clients shouldn’t be forced to depend on methods they do not use.

Image description

Solution:

Image description

Dependency Inversion Principle

It states that 




High-level module must not depend on the low-level module, but they should depend on abstractions.

Example:
Image description

Solution:

Image description

Image description

Advantages

  1. Maintainability
  2. Flexibility and Extensibility
  3. Readability and Understanding
  4. Quality Software

Happy coding!

Feel free like this blog and subscribe for more tech blogs.
Feel free to buy me a coffee: https://ko-fi.com/repanareddysekhar

Top comments (0)