SOLID Principles of OOP: Single Responsibility Principle

The SOLID principles form the most important principles of OOPS programming. They are best practices used to best design a class structure.


These five principles help us understand the need for certain design patterns and software architecture in general. So I believe that it is a topic that every developer should learn.


Regardless of whether it is clean code, object oriented programming, they all serve the same purpose: “To create understandable, readable, and testable code that many developers can collaboratively work on.”


The SOLID principles acronym is as below.

  • The Single Responsibility Principle

  • The Open-Closed Principle

  • The Liskov Substitution Principle

  • The Interface Segregation Principle

  • The Dependency Inversion Principle

We will look into the Single Responsibility principle in this blog.


The Single Responsibility Principle


This principle states that a class should only have one responsibility.

Furthermore, it should only have one reason to change.


Let’s see a few of its 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.

For example lets look at a class to represent a simple Meal.

In this code we store the name, description and price associated with an instance of a Meal.


Now lets add a couple of methods to query a meal name.


Now our Meal class works well, and we can store as many meals as we like in our application. But what’s the use of storing the information if we can’t output the name to our console and read it?


Let’s add a print method to the Meal class:

However, this code violates the single responsibility principle we outlined earlier.


To fix this, we should implement a separate class that deals only with printing out meal names:

Awesome. Not only have we developed a class that relieves the Meal of its printing duties, but we can also leverage our MealPrinter class to send our text to other media.


Whether it’s email, logging, or anything else, we have a separate class dedicated to this one concern.

29 views0 comments

Recent Posts

See All