SOLID Design Principles: The Single Responsibility

Nisanur Sakacı
Orion Innovation techClub
2 min readFeb 24, 2022

I. Introduction

SOLID principles allow writing “clean code” in object-oriented programming. Solid principles enable faster editing of the developed project.

Solid principles require 5 basic rules.

· S stands for SRP (Single Responsibility Principle)

· O stands for OCP (Open Closed Principle)

· L stands for LSP (Liskov Substitution Principle)

· I stand for ISP (Interface Segregation Principle)

· D stands for DIP (Dependency Inversion Principle).

II. S: Single Responsibility Principle (SRP)

According to the single responsibility principle, there should be only one function in each class. It is one of the fundamental principles that most developers apply to create solid and maintainable software. It can be applied not only to classes; but also to software components and microservices. If more than one purpose of a class does not follow this rule. The more responsibilities a class takes, the more chances it has to undergo.

The purpose of Single Responsibility is to facilitate changes to the code. Changes to the code may be required over time. With the single responsibility principle, changes can be easily corrected.

Codes written according to the single responsibility principle are like a regular drawer. Different tools in the drawer are placed in different classifications. This sequence makes daily life easier. Codes written according to SRP also make it easier to write code.

An example of a program can be given to SRP. Let a subscription reseller have four basic tasks: adding and deleting invoices, logging errors, and sending emails.
First of all, the program was written without using SRP.

Before SRP (All program)

Above is the written version of the program without using SRP. There are different functions with different tasks in the class. This usage makes it difficult for the programmer to understand and compile.

The program was edited and written using SRP. Different classes were created for each different task and operations were performed in these parts.

After SRP (Logger.cs)
After SRP (MailSender.cs)
After SRP (Invoice.cs)

--

--