SOLID : Open / Closed Principle

The Open / Closed Principle focuses on one basic requirement, the classes should be Open for extensions, but closed for modification.

The better way to explain the principle would be to first express the issue in hand. Consider the below class.

image

The class itself looks good, but what if in future one needs to add another Shape, say Circle. This would raise need to modify our existing class which is violation of OCP.

The solution to problem lies in achieving extension by deriving from abstraction. Let’s rewrite the code.

image

As you can see in the above implementation, we have created an abstract class with the function we might require extension. The corresponding classes, Square and Circle, implement this abstract class and extend its functionality. So when the requirements changes, and you need to extend, you needn’t change the existing classes. This means the classes which are properly tested needn’t be touched again and thereby reduce chances of introducing bugs in existing classes.

The Chain Of Responsibility Pattern is yet another way of achieving Open Closed Principle

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s