This is part two of a series of posts about the SOLID principles, for part 1 read The Single responsiblity principle (SRP) made practical
Today I’d like to try something different with you – I want you to jump into code with me. Fear not – its a toy example with little of code
I guess you know such pieces of code used here and there, nothing out of the usual – but what has become so common has a fatal problem: What happens when there’s change ?
Sometime, in the future, there would be another value added to this enum, and you would need to change this class. To add functionality you need to change code. And there are couple of problems with that:
- The class worked before you changed it, whose to say you didn’t damage it ?
- The class becomes longer and longer with each change, it would be harder to maintain and won’t have separation of concerns
- You can’t test in isolation your functionality, you have to test the class as a whole.
- The handler itself gets a mapping between message types and handlers
- The handler doesn’t know that are the different types (so adding a new type can’t affect it)
- The code have more classes – but each is small, simple and have a single responsibility
To add handling of new message results in adding code (and not changing it).
This is the heart of the open closed principle, the handler class is open to extension but closed for modification.
That’s it! Hope this post was fun to read as much as it was to write 🙂