The Open Closed Principle

The first sun-dried bricks were made in Mesopotamia (what is now Iraq), in the ancient city of Ur in about 4000 BC.

The Romans made use of fired bricks, and the Roman legions, which operated mobile kilns, introduced bricks to many parts of the empire. Roman bricks are often stamped with the mark of the legion that supervised their production.

In 1949, a carpenter from Denmark named Ole Kirk Christiansen started selling the Lego. Like previous bricks, the Lego was immutable, and could be used to create large structures. Unlike the bricks that came before it, Legos can be detached and replaced with other Legos, allowing structures to be redesigned and extended without destroying what came before.

The Open-Closed Principle (see the wonderful Uncle Bob article) describes a way of making our code more like Legos. The basic statement is that once a class is written and tested, it should never be changed. Changing our code turns our bricks back into mud, and can create huge cascades of failure. However, code that doesn’t change can be trusted to work the way it was previously written and tested to work.

The problem is this: requirements change. How do we change our programs if we can’t change our classes?

Our classes should be:

1) Closed for Modification….the source code for a module doesn’t change. Ever.

2) Open for Extension….the behavior of the class can be added to as requirements change.

You’ve seen this done throughout .NET. Controls fire events, and when those events are fired, all sorts of changes can be made. If our classes allowed others to listen to events, we could extend their behavior without changing them. A number of other patterns, including Façade, Command, and Chain of Responsibility, as well as simple inheritance and polymorphism can be used to provide openness for extension.

The use of re-usable, unchangeable bricks can make our coding easy, just like playing with Legos.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s