This is the first of five posts talking about the SOLID principles. This principles are a great guide to write good source code. Each post will talk about one of the principles:
- S Single responsability principle
- O Open/Closed principle
- L Liskov substitution principle
- I Interface segregation principle
- D Dependency inversion principle
Single responsability principle
One class must have only one responsability. Meaning with responsability any type of task, duty or obligation. The reasons for doing this is to make classes more robust, because if it has only one thing to do, the probability to change this class is lower than if it has multiple responsabilities. If multiple duties are solved with one class, the danger of introducing a bug to a duty when changing another is high.
This principle also helps a lot in order to make testable code, because is easier to test small classes with a few functionalities than hudge classes with tons of functions.
This User class has too many responsabilities:
Programming this way User class has too many dependencies. It depends on the file system, on the print system, and the UI. It’s better to distribute this behiviour through different classes.
This way the new classes are the ones how are dependant on the rest of the system and no the User class.