Archive

Posts Tagged ‘Clean code’

Open Closed Principle in Action

June 10, 2010 Comments off

Ivar Jacobson stated that all software entities change during their life cycle and this must be borne in mind when developing systems which are expected to last longer than the first version. A design principle which helps you with long lasting software is OCP (Open Closed Principle).

Open Closed Principle was coined by Bertrand Meyer. It states that “Software entities should be open for extension but closed for modification”.

When a single change to a program causes a cascade of changes to dependent modules  this is what we call as code smell or bad software design. The Open closed principle attacks this in a straight forward way. It states that you should design modules that should never change. However, when requirements change, our first reaction is to add or modify code. Right?

This seems odd because new application requirements warrants code changes in modules. It seems bizarre how these seemingly opposite attributes can be made to work together.

Figure 1 shows a simple design that does not confirm to “open closed principle”. Both Client and server classes are concrete. The client class uses the server class. If tomorrow, there is a need for the client class to use a different server class then the Client class must be changed to use the new Server class. This smells of tight coupling.

Figure 1

Figure 2 on the other hand shows us the corresponding design that conforms to the open closed principle. In this case AbstractServer is an abstract class and the client uses this abstraction. Now the Client class will use derived classes of the AbstractServer class. If we really want Client to use a different Server class, then a new derivative of the AbstractServer class can be created. The Client remains unchanged.

Read more…

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: