A class should have one and only one reason to change
Robert Cecil Martin
This is what was introduced by Robert Martin many years ago. We can translate it to like this: “A class has to be dedicated only for one purpose”, “A class has to be responsible for only one task”. You can also face a term like High/Low Cohesion of a class. High Cohesion basically stands for multiple responsibilities.
How do we benefit following this principle?
- Less code in single class – easier to read and understand
- Class code is focused on clear single task (responsibility) – easier to debug and maintain. If you deal with a class and understand its purpose, can be sure that no need to worry about any side behaviour of this class.
- Dependent classes are compiled only when really need to. In case of multi responsibility – change of logic in one of tasks which class is responsible for – would result in recompilation of dependent classes which use any of parent class tasks.
- Easier to use automated / unit testing. As a class has clear and bounded responsibility – easier to feed with input and assert output.
- Clear reusing of system component. You take and use class which does exactly what you need and nothing more.
Example
Wrong:
class Employee { int getSalaryAverage(); int setContacts(Contants cnt); void validateContacts(); }
Correct:
class Employee { int getSalaryAverage(); int setContacts(Contants cnt); } class Contancts{ void setName(String name); void setPhone(String name); void setEmail(String email); void validate(); }
The difference between Correct and Wrong is that contact validation is moved to Contacts class. Class Employee should take care only of what is directly related to Employee. Contacts is an atribute of employee, so thats fine if we can set them directly. But validation of contacts is business of Contacts class itself.
Check for other principles of SOLID in this post – SOLID Software Design Principles. Summary.