OOP-SOLID principle

Sureshkumar kajanthan
2 min readSep 20, 2022

--

In java, SOLID principles are an object-oriented approach that are applied to software structure design. These five principles have changed the world of object-oriented programming, and also changed the way of writing software.

The word SOLID acronym for:

  • Single Responsibility Principle (SRP)
  • Open-Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

1.Single Responsibility Principle(SRP)

The idea behind the SRP is that every class, module, or function in a program should have one responsibility/purpose in a program. As a commonly used definition, “every class should have only one reason to change”.

consider the example below:

The class above violates the single responsibility principle.

Why?

This Student class has three responsibilities

  • registerStudent
  • calculate_Student_Results
  • sendEmail

The above code snippet violates the single responsibility principle. To achieve the goal of the principle, we should implement a separate class that performs a single functionality only.

Now let’s fix this!

Now we’ve separated each functionality in our program. We can call the classes anywhere we want to use them in our code.

The examples we used use just showed each class having one method — this is mainly for simplicity. You can have as many methods as you want but they should be linked to the responsibility of the class.

Now that we have separated the logic, our code is easier to understand as each core functionality has its own class. We can test for errors more efficiently.

The code is now reusable. Before, we could only use these functionalities inside one class but now they can be used in any class.

The code is also easily maintainable and scalable because instead of reading interconnected lines of code, we have separated concerns so we can focus on the features we want to work on.

“every class should have only one reason to change”.

2.Open-Closed Principle (OCP)

--

--

No responses yet