First SOLID Principle — Single Responsibility Principle (SRP) applied to Java with Spring Boot

Daniel Angel
3 min readJul 23, 2023

--

topical tips

The first SOLID principle is the Single Responsibility Principle (SRP). This principle states that a class should have only one reason to change, meaning it should have a single responsibility in the system. This implies that each class should have a well-defined purpose and focus on a single task or functionality. By adhering to SRP, we can achieve clearer, maintainable, and extensible code.

Applying SRP to Java with Spring Boot:

When developing applications using Java and Spring Boot, we can apply SRP by following some key guidelines:

  1. Separation of Concerns: Each class should be responsible for a single function or task in the system. If a class has multiple responsibilities, it can become challenging to maintain and understand how different functionalities are related.
  2. Use of Services: In Spring Boot, we can create service classes that handle specific business logic. Each service should be focused on a particular task and be reusable in different parts of the system.
  3. Clean Controller Classes: In the context of a controller in Spring Boot, we should keep the handling of HTTP requests simple and delegate the business logic to corresponding services.
  4. Avoid God Classes: Avoid creating classes that do everything or become “God” classes that encompass too many functionalities. Instead, divide tasks into smaller, cohesive classes.

Code Example Applying SRP in Java with Spring Boot:

Let’s assume we are developing an employee management application. We’ll apply SRP to maintain proper separation of responsibilities.

// Service Class for Employee Business Logic
@Service
public class EmployeeService {
public List<Employee> getAllEmployees() {
// Logic to fetch all employees from the database
}

public void saveEmployee(Employee employee) {
// Logic to save a new employee to the database
}

public void updateEmployee(Employee employee) {
// Logic to update employee details in the database
}

public void deleteEmployee(int employeeId) {
// Logic to delete an employee from the database by ID
}
}

// Controller Class to Handle Employee-related HTTP Requests
@RestController
@RequestMapping("/employees") // Set base path for all employee-related endpoints
public class EmployeeController {
private final EmployeeService employeeService;

public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@GetMapping
public ResponseEntity<List<Employee>> getAllEmployees() {
List<Employee> employees = employeeService.getAllEmployees();
return ResponseEntity.ok(employees); // HTTP 200 OK
}

@PostMapping
public ResponseEntity<String> addEmployee(@RequestBody Employee employee) {
employeeService.saveEmployee(employee);
return ResponseEntity.status(HttpStatus.CREATED).body("Employee created successfully."); // HTTP 201 Created
}

@PutMapping("/{id}")
public ResponseEntity<String> updateEmployee(@PathVariable int id, @RequestBody Employee employee) {
boolean employeeExists = employeeService.updateEmployee(id, employee);
if (employeeExists) {
return ResponseEntity.ok("Employee updated successfully."); // HTTP 200 OK
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Employee not found."); // HTTP 404 Not Found
}
}

@DeleteMapping("/{id}")
public ResponseEntity<String> deleteEmployee(@PathVariable int id) {
boolean employeeExists = employeeService.deleteEmployee(id);
if (employeeExists) {
return ResponseEntity.ok("Employee deleted successfully."); // HTTP 200 OK
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Employee not found."); // HTTP 404 Not Found
}
}
}

In this example, we have applied the Single Responsibility Principle (SRP) by separating responsibilities into different classes. The EmployeeService class is responsible for the business logic related to employees, while the EmployeeController class focuses on handling HTTP requests and delegates the business logic to the EmployeeService.

How it’s usually done without applying SRP:

Without applying SRP, we might have a single EmployeeController class that handles both HTTP requests and employee business logic. This would result in an overloaded class with multiple responsibilities, making it difficult to understand and maintain the code as the application grows.

I hope this article has helped you understand how to apply the Single Responsibility Principle (SRP) in Java with Spring Boot to develop cleaner and more maintainable code. If you have further questions or need more examples, feel free to ask. Happy coding!

Note

I am pleased to announce that I will be publishing a series of short articles focused on the SOLID Principles in programming. The SOLID Principles are a set of fundamental guidelines that assist developers in writing high-quality, flexible, and maintainable code. Each article will be dedicated to a specific principle, where I will explain it concisely and provide practical examples for its application in the context of Java and Spring Boot programming.

#tech #Java #solid

--

--

Daniel Angel
Daniel Angel

Written by Daniel Angel

Backend developer | Java, Spring boot, Cloud| Laravel, Php

No responses yet