The King of Abstraction

Open/Closed Principle, OCP, is the idea that classes and methods should be developed that they will not need to be changed in the future. With an appropriate care for abstacting the classes the developer can reuse those classes and add additional features through inheritance and overriding. Allowing classes to be abstract has an additional bonus of allowing the code to be loosely coupled and will create huge opportunities for modularity, thus creating a less confusing codebase. 

 

In Practice

In this example we will show an example of poorly designed code, then show you how to rewrite the code to impliment OCP.

Poorly planned code:

public class Pet
{
    public string Type { get; set; }

    public string MakeSound()
    {
        if (Type == "Dog")
        {
            return "Bark";
        }
        else if (Type == "Cat")
        {
            return "Meow";
        }

        return "Unknown sound";
    }
}

 

 

Heres how we can create code that will be flexable enough to be reused by keeping the design modular:

 

Refactored to follow Open/Closed Principle:

// Define an abstract base class for pets
public abstract class Pet
{
    public abstract string MakeSound();
}

// Dog class extending Pet
public class Dog : Pet
{
    public override string MakeSound()
    {
        return "Bark";
    }
}

// Cat class extending Pet
public class Cat : Pet
{
    public override string MakeSound()
    {
        return "Meow";
    }
}