If you are able to express something you learnt in a simple manner, then you can be confident that you knew it well enough. This blog is an attempt by a learner to prove the above fact.

Sunday, March 28, 2010

Open Closed Principle

A Design principle is a basic tool or technique that can be applied for designing or writing code to make that code more maintainable, flexible or extensible. Open Closed Principle is one of the Design Principle.

Definition :
          Classes should be open for extension and closed for modification

Ex : class FlyingObject()
       {
           fly()
           {
                  //common behavior for all flying objects
           }
        }

      class Bird extends FlyingObject
      {
           fly()
          {
               //use the common behavior from FlyingObject + specific flying behavior of the Bird
          }
       }

     class Aeroplane extends FlyingObject
     {
          fly()
          {
                 //use the common behavior from FlyingObject + specific flying behavior of the Aeroplane
          }
     }

  Here, fly() method in Class FlyingObject is closed for modification but open for extension through     inheritance in its subclasses.


OCP is all about allowing change, but doing it without any modification to existing code i.e., it lets you extend your working code, without changing that code.

OCP is about flexibility, and goes beyond just inheritance. Composition is another way to achieve it.

Inheritance is a simple example of OCP, but anytime your code is closed for modification but open for extension, you are using OCP.

Simple Scenario :
If you have a private method closed for modification but have a public method that invoked the private method, you are extending the behavior of the private methods, without changing them.

OCP is really a combination of encapsulation and abstraction. In the above example, common behavior for all flying objects is abstracted and placed in base class, thus locking the code up from modification. Behaviour for fly() in Bird class needs an extension from the common behavior and it differs from fly() behavior in Aeroplane. Thus by encapsulating what varies from what stays the same, you are allowing behavior extension in subclasses.

No comments:

Post a Comment

About Me

My photo
Hyderabad, Telangana , India
I may NOT be what my MIND thinks. I believe I am what my HEART feels. I am a drop in an ocean if ocean is the divinity. The moment drop merges into ocean, it loses its identity. So am I. Until then I am what I am, eagerly awaiting for the merger.