The Open closed principle (The Why&How)

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

The repository is located here and the class I want you to look at is here.

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:

  1. The class worked before you changed it, whose to say you didn’t damage it ?
  2. The class becomes longer and longer with each change, it would be harder to maintain and won’t have separation of concerns
  3. You can’t test in isolation your functionality, you have to test the class as a whole.

Look at the changed code and the use case (you can browse the rest of the code in the repository) and lets note some differences in the outcome:

  1. The handler itself gets a mapping between message types and handlers
  2. The handler doesn’t know that are the different types (so adding a new type can’t affect it)
  3. 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 🙂




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: