Open Close Principle(OCP)

Motivation

A clever application design and the code writing part should take care of the frequent changes that are done during the development and the maintaining phase of an application. Usually, many changes are involved when a new functionality is added to an application. Those changes in the existing code should be minimized, since it's assumed that the existing code is already unit tested and changes in already written code might affect the existing functionality in an unwanted manner.

The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Intent

Software entities like classes, modules and functions should be open for extension but closed for modifications.

Violation of OCP

Problem with above design

What if a new shape need to be introduced, let's say Triangle? We need to do below steps in order to make it work with existing design

  1. Create Triangle class

    1. Extend from Shape

    2. Initialize type instance variable of Shape class in Triangle constructor

    3. create drawTriangle method

  2. Modify GraphicEditor class

    1. Add one more else-if block for Triangle

    2. Add drawTriangle method

Point number 2. Modify GraphicEditor class represent bad design

What problems this bad design

  • for each new shape added the unit testing of the GraphicEditor should be redone.

  • when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.

  • adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly


Complying with OCP