Good Code Abides By The Open-Closed Principle

Def: “In object-oriented programming, the open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“; that is, such an entity can allow its behaviour to be extended without modifying its source code.” – wikipedia

In layman terms, what the principle states is that the objects you create should be stable enough to achieve todays requirements but flexible enough that they don’t have to change every time the requirements change. The application can be enhanced and improved without having to tear it down first and write everything again from the start. Any improvement or new functionality can be easily added while keeping as much of the existing code unchanged.

This is good and all in theory but how do we apply this in practice?

Well, as we previously stated, we want to be able to introduce new behaviour in an existing environment or system. And since we hate having to do work twice, we will introduce this new functionality or behaviour with the aid of newly created objects rather than modifying the old ones. Think of it like a “plug-in” since that’s how new new design features should act like & be implemented.

The biggest advantage applying this principle offers is by creating stability. Objects that do not require change are dependable objects. This in turn means we can confidently call upon these objects to elicit their behaviour in new ways instead of having to duplicate code or do the work from the top each and every time something must change. And change is inevitable, just like in life. The only static environments are dead ones, your application is alive.

Now keep in mind that this principle like all others acts like a guide-line. It is not set in stone. You have to decide the extent of it’s application. Extensive use of this principle might lead to the creation of innumerable and arguably unnecessary wrapper objects that could probably make your application harder to understand and maintain. You have to draw the line on it’s use so that the gains warrant the costs.

So keep you methods as abstract as possible, make sure they abide by the Single Responsibility Principle , keep your Classes coherent with good flexible interfaces and you’ll do fine.

0 comments… add one

Leave a Comment