Tuesday, December 18, 2018

Open Closed Principle

This is part two of a five part series about SOLID class design principles by Robert C. Martin. The SOLID principles focus on achieving code that is maintainable, robust, and reusable. In this post, I will discuss the Open Closed Principle.
The Open Closed Principle (OCP): You should be able to extend a classes behavior, without modifying it.
The OCP is sometimes alternatively defined as:
A class should be open to extension, but closed to modification.
Robert Martin sums up the rationale for the OCP like this:
"When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with 'bad' design. The program becomes fragile, rigid, unpredictable and unreusable. The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works." — Robert Martin

The Benefits

As stated by Robert Martin, classes that must be modified to accommodate new changes are fragile, rigid, unpredictable and unreusable. By insulating the class from changes, the class becomes robust, flexible, and reusable. Also as no modifications are made to the code no bugs can be introduced, leading to code that only becomes more stable over time through testing. The ability to reuse a class that has been working for years without modification is clearly preferable to modifying the class every time requirements change.

No comments:

Post a Comment