SOLID Principles Illustrated By Examples: 1. Single Responsibility Principle(SRP)

Manoj Chemate
ILLUMINATION
Published in
2 min readDec 6, 2022

This is the first article in a series of articles on SOLID design principles introduced by Robert C. Martin (Uncle Bob).

SOLID is a mnemonic acronym for five design principles intended to make object-oriented designs more understandable, flexible, and maintainable.

  1. Single Responsibility Principle
  2. Open Closed Principle
  3. Liskov Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion Principle

Let’s talk about the Single Responsibility Principle (SRP),

As a developer do you remember saying this,

but I didn’t change that function, why is it breaking?

Photo by Brett Jordan on Unsplash

If yes then most likely the author of the code has not followed the SRP which says,

A module should have single responsibility.

More informally, A class, interface, or function should only perform one type of task.

If your class name is Logger it should be logging things, if your class name is Validator it should only be validating things, and class ExceptionHandler should only be handling exceptions. This ensures future changes in one class will affect only that functionality and don’t need to care about the rest of the code.

Let’s take a look at the sample example below,

Count the number of things the incrementPay() method is doing here,

It is performing validations and opening/closing of database connection, slack messages, and exceptions, it is not just incrementing payment as its name suggests.

Look at the code below having minimal responsibility,

Which just increments the salary and saves it to the database. The task of calculating increments and managing database connections is delegated to other classes.

Having followed SRP,

  1. Ensures that change in one part won’t affect other parts of the system.
  2. The code is more readable and maintainable.

that’s it for SRP, check out the next Open-Closed principle here

--

--

Manoj Chemate
ILLUMINATION

Software Engineer, I write about my experience with Java, Spring, Micro-services, gRPC, REST, Data Structures, Algorithms, and Software Engineering Interviews.