This is the second 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
Any sowftware entity, like the source code or classes, must be open to expand, and closed to change. You must include new funtionality to a class without changing the previous functions.
Ways to expand functionality
There is only one ways to expand the methods of one class: using inheritance
There is two types of inheritance to expand code:
- Use a specialized class to include new functionality or improve the previous one.
- The other way is to expond some beheviours of the code to abstract classes (like Swift protocols), to be implemented in the future
This shape class has two responsabilities, to be a circle and sometimes a square
It’s better to define two classes, one for each responsability
It’s easier to mantain and to expand. This way it can be possible to expand the code with new shapes without changing the rest of the classes.