Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
611 views
in Blog Post by 39 42 54
edited by

What's the Open Closed Principle?

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

Example Description:

I aim to enhance my application's functionality by initially implementing a summation operation for two numbers. Over time, I plan to gradually introduce additional operations such as subtraction and division. As time progresses, my goal is to expand the capabilities further, eventually incorporating a division operation.

To achieve this, I will structure my code by creating separate classes and functions for each operation, ensuring a modular and scalable design without the need for constant modifications to the initial class and function.

Example: 

  • NOT PREFERRED

  • PREFERRED
public abstract class Calculator
{
    public abstract void Operation(double number1, double number2);
}
public class Addition : Calculator
{
    public override void Operation(double number1, double number2)
    {
        Console.WriteLine(number1 + number2);
    }
}
public class Division : Calculator
{
    public override void Operation(double number1, double number2)
    {
        Console.WriteLine(number1 / number2);
    }
}
public class Multiplication : Calculator
{
    public override void Operation(double number1, double number2)
    {
        Console.WriteLine(number1 * number2);
    }
}
 public class Subtraction : Calculator
 {
     public override void Operation(double number1, double number2)
     {
         Console.WriteLine(number1 - number2);
     }
 }

See Also


If you don’t ask, the answer is always NO!
...