SOLID — Single Responsibility Principle

Lucas Schwenke
3 min readFeb 6, 2022

Hello everyone, how are you today? In the Oriented Object world, there are many patterns and good practices to do; one of them is SOLID!

But what is SOLID? 🤔

SOLID is an acronym created by Robert C. Martin (your dear Uncle Bob). Uncle Bob defined five principles:

  • S — Single Responsibility Principle
  • O — Open Closed Principle
  • L — Liskov Substitution Principle
  • I — Interface Segregation Principle
  • D — Dependency Inversion Principle

These principles help developers create a better, more legible, and codes cleaner. In the Oriented Object is essential to know about these principles.

This article will see the first one, the Single Responsibility Principle. The examples were written in Kotlin, but the essential idea applies to any programming language!

S — Single Responsibility Principle

A class should have one and only one reason to change, meaning that a class should have only one job.

According to uncle Bob, a class should have one reason to change, and only one. So the class should specialize in one specific subject and has one responsibility.

It's wrong to write "God class." But what is a God class? God class is a class that has many subjects and many responsibilities. God class is hard to write tests, a coupled code, and other bad things. Avoid writing God classes, ok?

So let's check a God class example:

Let's check this God class. We have four responsibilities for two different subjects, User and Order. This class creates a new user, updates an existing user, sends an email confirmation, and creates a new user order. Wow, many responsibilities, no?

We are violating the SRP principle, and our code is hard to write tests, is not reusable, and has a significant cohesion.

Now let's put the SRP principle in our code! The UserService will be broken into some classes; the first one is to create a new User; this class has a responsibility to create a user, just it:

Is it cleaner, right? Just has one responsibility and deal with a one subject. Let's do it in the others classes:

Now your God class was broken into four new classes, each one having your specific responsibility and dealing with a one subject.

Now we can reuse the classes, write tests much better, have lower cohesion, and be easier to write and understand.

We can apply the SRP in functions (methods) too! Let's see a bad example and use the principle:

The function createUser has three responsibilities, so now let's refactor this function:

Now each function has our responsibility! Much better, what do you think?

The SRP is the base of the other principles; we will see them in the next articles. You can see the complete code in this repository.

I will see you in the next article!

References:

--

--

Lucas Schwenke

Senior Software Engineer. 28 years old. Backend engineer, Kotlin and Java.