SOLID – Open/Closed Principle

Definition:

it states that the software entities (classes, modules, functions,..etc.) should be open for extension but closed for modification.

in this principle we want to be able to add a new behavior ‘open to extension’. without the need to change our source or binary code ‘closed to modification’. or in other words we should strive to write code that doesn’t have to be changed every time the requirements change.

huh! change behavior without changing the code. !!

Yes we can achieve this by relying on abstraction (Interfaces, Abstract Base Classes) because there is no limit to number of different ways we can implement that abstraction .

An Example :

Suppose that there is a class called Rectangle that has a width and height properties within it.

rectangleclass

and a class called AreaCalculator that calculates the area of the rectangle by multiplying its width and Height.

24-4-2013 4-47-15 PM

Now every thing works fine but what if we want to add another feature to AreaCalculator class that makes it able to
calculate the area of circle too.

hmmm… there will be no problem with that .

first I’ll make a circle class

circleClass

then I will update my AreaCalculator class to be like this :

AreaCalculator

once again what if we want to extend our AreaCalculator class to also calculate the area of a triangle too.

Of course in this very basic example it is not hard for us to implement it but it does require us to modify the code again and this is not good .Imagine In a real world example where the code is ten, a hundred or a thousand times larger, modifying the class everytime a new requirement is needed can be a pretty big problem .

So we want to close our AreaCalculator for modification and make it open for extension.

The Solution:

I’ll create a base class called shape for both rectangles, circles and any other shapes that will be added in the future. the shape class defines an abstract method for calculating it’s area.

ShapeClass

and both the Rectangle and the Circle classes will inherit from the Shape class:

Rectangle and Circle from shape

As the Area method in the base class ‘Shape’ is abstract then the two area methods inside the Circle and Rectangle classes will override it and each one will provide its own implementation of the method.

newAreaCalculator

Now the Area method of the AreaCalculator class is not responsible for the actual calculating of the area it can deal with any type of shapes we throw at it and the code is much simpler.

Related Posts:
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