jueves, 8 de agosto de 2013

Single Responsability Principle

This term was first introduced by Robert C. Martin, the author of the Clean Code Book. And what he wants to teach us is that a class must have only one responsibility. But wait!!, what  is a responsibility? Well Robert C Martin says that a responsibility is a reason to change.
The advantages of applying the SRP in our work are:  
We are going to obtain classes more robust and focused.
Code complexity is reduced.
Readability
Clearer code

As an example we can consider a system of a company in which there is a class that has methods that deal with business rules, reports and also the database (the example showed by Uncle Bob in the video of Clean Code):

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

As we can see here is violated the SRP because  calculatePay() will change whenever the business rules change for calculate the salary. In reportHours(), the case for change is when someone wants a different format to do a report. And finally save()  will change when the schema of the DB changes.
So how do we fix that, and fulfill this principle?
Well, we have to split this into different classes, in this case 3 because the class below has 3 reasons to change as I explained earlier. So the result could be:

public class Employee{
         public Money calculatePay(){…}
}

public class EmployeeReport{
         public String reportHours(Employee e){…}
}

public class EmployeeStore{
         public void save(Employee e){…}
}

No hay comentarios:

Publicar un comentario