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