OCP - Open/Closed Principle

A new week, a new principle :) 

Ivar Jacobson said: "All systems change during their life cycles, so how can we create designs that are stable in the face of change and that will last longer than the first version?"
Nothing to fear Ivar
OCP to the rescue.

No, not this OCP


OCP - Open/Closed Principle

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
When a single change to a program results in a cascade of changes to dependent modules, the design smells of rigidity. If OCP is well applied, further changes of that kind are achieved by adding
new code, not by changing old code that already works.

By using abstractions we can achieve open for extension (behaviour of a module can be extended) and closed for modification (extending the behaviour does not results in changes to the rest of the code).




In old procedure style languages if we wanted to implement different shapes we would have some kind of struct or enum. And then we would repeat a switch statement or several ifs all across the application. With each new shape we would have to search for all places that must be changed.


With OCP in and objected oriented language this is converted to:
Izzz nice :D


But how to know which changes are likely? We do appropriate research, ask questions, and use our experience and common sense. After all that, we WAIT until the changes happen!

Common sense... fail

Fool me once... First we should write or code expecting it not to change. When it does (and it will) we implement the abstractions that protect us from changes of that king. In short we take
the first bullet and then make sure we are protected from any more bullets coming from that particular gun :)


Man you're not Robocop!

Using OCP will result in increased flexibility, re-usability and maintainability. However be warned: Resisting premature abstraction is as important as abstraction itself.

And this guy has a special set of skills...

No comments:

Post a Comment