Open for extension closed for modification. This means that our code is written in such a way that our class can have new behaviour without changing its structure.
Lets say that we have a Task
and this task can have a description, a status and a couple of on/off characteristics like the fact that can be edited, shared or tracked.
Using flags
One way to depict this in code is by using flags in the form of booleans:
This means that every time we need to add a new characteristic we have to modify the Task
class and add a new boolean property. This violates the open close principle making the code difficult to scale.
Using a list of enums
Another way is to replace all these flags with a list of enums:
Now if we need to add a new characteristic we simply add a new enum entry and the entire project can keep using the hasCharacteristic
method to query a task for its characteristics.
Bonus benefit: this way we also avoid the wall of properties that sometimes hides information instead of revealing it!