Open Closed Principle

Open closed principle

What is Open Closed Principle?

Open Closed Principle, also known as OCP is the second principle from the set of SOLID Principles.

Software entities (classes, modules, methods, etc.) should be open for extension, but closed for modification.

That means if you want to extend some behaviors of a class then do it by extending the class instead of updating it. There are multiple ways of doing that. For example, inheritance, delegates, extension methods, etc.

Extending the behavior of a class by modifying its code will cause the below problems.

  1. The class will grow large and will be difficult to manage.
  2. Adding a new behaviour will lead to frequent modification of the class.
  3. It will also require more amount of testing.

Let’s take an example for Animal class. See how it can break OCP and how to fix that.

Animal class support cat and a dog. Look at the code snippet below

class Animal
{
    public string Type { get; set; }
    public void MakeSound()
    {
	if(Type == "Dog")
        {
	       //Bark
        }
	else if(Type == "Cat")
        {
		//Meow
        }
    }
}

How does it break OCP?

If want to add one more type of animal then you have to make changes in MakeSound() method. There can be tens of thousands of Animals. Adding them all will make the class extremely large and the class will be very difficult to manage.

How to fix OCP violation?

Solution: Create an interface and implement behaviors in extending classes.

interface IAnimal
{
	void MakeSound();
}
class Dog: IAnimal
{
    public void MakeSound()
    {
		//bark
    }
}
class Cat : IAnimal
{
	public void MakeSound()
	{
		//Meow
	}
}

Now you can add any number of animals without modifying the existing code but you need to change its call from

Animal animal = new Animal();
animal.MakeSound("Dog");

to

IAnimal dog = new Dog();
dog.MakeSound();
Open closed principle

Leave a Reply

Your email address will not be published.

Coding Crest Back To The Top