Software Design - Single Responsibility Principle - with examples


Image


For me, Single Responsibility Principle (SRP) is the most important design principle.

What is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let’s get started.

Free Courses - Learn in 10 Steps

What will you learn?

  • What is the Single Responsibility Principle?
  • How do you apply this principle in developing and designing software applications?

Software Design Principles

This is the fourth article in a series of articles on important Software Design Principles:

What Is The Single Responsibility Principle (SRP)?

As the term says, this principle is all about having single responsibility.

In any software system, this principle is applicable at multiple levels

  • a variable
  • a method
  • a class
  • a package
  • a component
  • application layers or
  • the entire application itself

SRP For Methods

Any method that you write should have a single responsibility - it should either be a high-level method, or a low-level one. Only when a method has a single responsibility, you will be able to give it an appropriate name.

SRP For Classes

“A class should have one, and only one reason to change”

Let’s now have a look at a few examples of classes that violate this principle, and then look at how to correct the violation.

Example 1: The Task class


	public class Task {
		public void downloadFile(Strign location) {
			//...
		}

		public void parseTheFile(File file) {
			//...
		}

		public void persistTheData(Data data) {
			//...
		}
	}

Does the class Task adhere to the single responsibility principle? Not at all, because it does a lot of different things:

  • downloadFile() downloads the file, by communicating over the internet
  • parseTheFile() parses the file contents
  • persistTheData() saves the data into a database

A better solution would be to have separate classes for each of the responsibilities currently taken up by Task. Here is one such solution.

Identifying The Low-level Classes


	public class FileDownloader {
		public void downloadFile() {
			//...
		}
	}

	public class DataParser {
		public void parseData() {
			//...
		}
	}

	public class DatabaseStorer {
		public void storeIntoDatabase() {
			//...
		}
	}

  • FileDownloader only downloads the file from the internet
  • DataParser only parses the downloaded file
  • DatabaseStorer only stores the parsed data, into the database

These are all low-level classes here.

Adding A High-Level Class

	public class DownloadAndStore {
		public void doEverything() {
			new FileDownloader().downloadFile();
			new DataParser().parseData();
			new DatabaseStorer().storeIntoDatabase();
		}
	}

Then, you can create a high-level class such as DownloadAndStore that invokes the functionality of these low-level classes to perform the complete task. Such an organization ensures that the low-level classes are reusable.

Example 2: The Employee Class

Consider next, the Employee class shown below:


	public class Employee {
		public Money calculatePay() {
			//...
		}
		public String reportHours() {
			//...
		}
		public void save() {
			//...
		}
	}

Employee concerns itself with not just calculating the pay of an employee, but also reporting hours for work, and saving these details to the database.

I will leave it as an exercise to fix the Employee class to adhere to SRP.

SRP For Components

Every enterprise application has parts of its functionality organized as Components. For example, have a look at the diagram below:

image info

Here, the following components are of note:

  • Security component takes care of user authentication and authorization. Designing such a component helps abstract applications from the low-level security details. All microservices can interact with this component to find out if a user has access.
  • The Logging component - does the low level logging functionality
  • The Archetype component - Can be used to create new microservices

Each of these components have a single responsibility. If the Security component takes care of logging, it would become less reusable. Therefore, at the component level, a well-defined single responsibility is highly desirable.

Using SRP For Common Infrastructure

image info

In the diagram shown above, you can identify the following infrastructure components:

  • Naming Service - Has the responsibility to retrieve the service location based on its name
  • API Gateway - All requests go through the API Gateway. Common features like authentication, logging, rate limiting can be implemented in an API Gateway.
  • Centralized Logging - Centralized store for logs from all microservices so that we can easily debug problems

Even with these sub-systems, a single responsibility for each of them is most desirable.

Using SRP For Application Layering

Single responsibility is also an important factor in how you layer your application. Have a look at the following conceptual layers in a web application:

image info

  • Web Layer: All functionality concerned with direct user interaction sits here
  • Business Layer: Houses the core business logic
  • Data layer: All the functionality dealing with storing and retrieving data goes here

If you had the need to talk to other systems, there would have been an additional Enterprise Messaging Layer added onto this setup.

Summary

In this article, we talked about the Single Responsibility Principle. It is applicable at multiple levels to the parts of an application. This includes methods, classes, packages, components and application layers. With regards to classes, at a low level it means a class has only one reason to change.

In general, Single Responsibility ensures high cohesion, low coupling and enhanced reusability.

Do check out our video on this:

image info

Best Selling Udemy Courses

Image
Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure


Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes


Subscribe

FREE COURSES



Related Posts

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.

Spring Boot Tutorial For Beginners in 10 Steps

Introduction to Spring Boot in 10 Steps. Learn the basics of Spring Boot setting up a basic project example with Spring Boot.

Spring Framework Tutorial for Beginners - Your First 10 Steps

Learn the basics of Spring Framework setting up a very simple example.

JPA and Hibernate Tutorial using Spring Boot Data JPA

Complete journey starting from JDBC to JPA to Spring Data JPA using an example with Spring Boot Data JPA starter project. We use Hibernate as the JPA Implementation.

Creating a Web Application with Spring Boot with JSP

Setting up a basic web application with Spring Boot is a cake walk. We will create a simple web application using Spring Initializr and add JSP features to it.

What is Spring Boot Auto Configuration?

Auto Configuration is the most important feature in Spring Boot. In this tutorial, we will learn important concepts about Auto Configuration with a couple of examples.

Unit Testing Rest Services with Spring Boot and JUnit

Setting up a Basic REST Service with Spring Boot is a cake walk. We will go one step further and add great unit tests to our RESTful Service.


Search