Single Responsability Principle (SOLID first principle)with Java example.

Bruno Souza
3 min readJun 14, 2023

--

The Single Responsibility Principle (SRP) is a design principle in software engineering that states that a class or module should have only one reason to change. In other words, it emphasizes that a class should have a single responsibility or purpose.

The principle was introduced by Robert C. Martin, also known as Uncle Bob, and it is one of the five principles of SOLID, a set of guidelines for designing maintainable and flexible software systems.

According to the SRP, a class should have a clear and well-defined responsibility, encapsulating a single functionality or behavior. This means that the class should be focused on performing a specific task or providing a specific service. If a class has multiple responsibilities, it becomes more difficult to understand, maintain, and modify over time.

The primary motivation behind the SRP is to achieve high cohesion and low coupling in software systems. Cohesion refers to how closely the members of a class are related to each other, while coupling refers to the interdependencies between different modules or classes. By having a single responsibility, a class can have high cohesion because all its members are closely related and work together to fulfill that responsibility. At the same time, it can have low coupling because it has minimal dependencies on other classes or modules.

By adhering to the SRP, software systems become more modular, easier to understand, test, and maintain. Changes or modifications to a particular responsibility can be isolated to a single class, without affecting other unrelated parts of the system. This principle also promotes code reusability since classes with well-defined responsibilities can be easily used in other contexts.

It’s important to note that applying the SRP doesn’t mean creating excessively small classes for every single action or method. The goal is to strike a balance and define responsibilities at a meaningful level of abstraction, considering the context and requirements of the system.

Overall, the Single Responsibility Principle promotes clean, maintainable, and loosely coupled code by advocating for the separation of concerns and the creation of focused and cohesive classes.

Bellow, i bring an example of SRP in code, based on Java 11

public class Funcionario {

private String nome;
private String cpf;
private Cargo cargo;
private BigDecimal salario;
private LocalDate dataUltimoReajuste;

public Funcionario(String nome, String cpf, Cargo cargo, BigDecimal salario) {
this.nome = nome;
this.cpf = cpf;
this.cargo = cargo;
this.salario = salario;
}

/* Trecho removido pelo principio S do SOLID
Logica abaixo gera mais de uma responsabilidade a classe, diminuindo a coesao e aumentando o acoplamento

public void reajustarSalario(BigDecimal aumento) {
BigDecimal percentualReajuste = aumento.divide(salario, RoundingMode.HALF_UP);
if (percentualReajuste.compareTo(new BigDecimal("0.4")) > 0) {
throw new ValidacaoException("Reajuste nao pode ser superior a 40% do salario!");
}
this.salario = this.salario.add(aumento);
this.dataUltimoReajuste = LocalDate.now();
}
*/

// Método abaixo é utilizado por uma classe de serviço generica para atualizacao de salario
public void aumentaSalario(BigDecimal novoSalario) {
this.salario = novoSalario;
dataUltimoReajuste = LocalDate.now();

}

public String getNome() {
return nome;
}

public void setNome(String nome) {
this.nome = nome;
}

public String getCpf() {
return cpf;
}

public void setCpf(String cpf) {
this.cpf = cpf;
}

public Cargo getCargo() {
return cargo;
}

public void setCargo(Cargo cargo) {
this.cargo = cargo;
}

public BigDecimal getSalario() {
return salario;
}

public void setSalario(BigDecimal salario) {
this.salario = salario;
}

public LocalDate getDataUltimoReajuste() {
return dataUltimoReajuste;
}

public void setDataUltimoReajuste(LocalDate dataUltimoReajuste) {
this.dataUltimoReajuste = dataUltimoReajuste;
}

}

This example, show how to make a model class using the SRP principle, the commented code show how to dont make a model class, hurting the SRP principle.

/* Classe criada com o intuito de demonstrar o principio S (Single Reponsability Principle) do SOLID
Criamos o servico abaixo para remover esta regra de megocio da classe Funcionario
A logica abaixo traria mais de uma rspoinsabilidade a classe funcionario
A logica abaico poderia acarretar em alterações na classe funcionario desnecessariamente
*/

public class ReajusteService {
public void reajustarSalario(BigDecimal aumento, Funcionario funcionario) {
BigDecimal percentualReajuste = aumento.divide(funcionario.getSalario(), RoundingMode.HALF_UP);
if (percentualReajuste.compareTo(new BigDecimal("0.4")) > 0) {
throw new ValidacaoException("Reajuste nao pode ser superior a 40% do salario!");
}

BigDecimal salarioAjustado = funcionario.getSalario().add(aumento);
funcionario.aumentaSalario(salarioAjustado);
}
}

In here, this class, show how to fix the problem in the model class.

--

--