Open close principle is a software design concept that tends to make a software design flexible enough for extension yet closed for modification. In other words adding new feature(s) to an existing source code is done by adding new classes rather than changing the core source code and structure.

Let’s try to implement a SoundProducer that outputs the sound of a Guitar in a way that violates the open close principle (see the next diagram). Now, in order to support a new musical instrument (Piano); we will have to change the main SoundProducer class to play the new instrument sound, and then after a short while the Flute came, and then the Clarinet, and then the Oboe, and …etc. The more instruments to support the more likely the SoundProducer class will change.

A good design will make the SoundProducer closed for modification, yet opened for extension (see the next diagram) and this by making the SoundProducer depend on abstraction (Instrument), now adding a new instrument (feature) will be done only by adding a new class extending the abstract Instrument class and implement its abstract method playSound without any changes done on the main SoundProducer class.

Leave a Reply

Your email address will not be published.

Captcha Time limit is exhausted. Please reload the CAPTCHA.