SOLID & Design Patterns Interview Question #4

What is the Open/Closed Principle (OCP)?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

The Open/Closed Principle says software entities should be open for extension but closed for modification. New behavior should often be added by introducing a new implementation rather than repeatedly editing stable conditional logic.

Detailed Explanation

The Open/Closed Principle says software entities should be open for extension but closed for modification. New behavior should often be added by introducing a new implementation rather than repeatedly editing stable conditional logic.

Interfaces, polymorphism, composition, and strategies are common ways to support OCP. The principle should be applied where variation is expected, not by creating abstractions for every line of code.

Code Example

public interface IDiscountStrategy
{
    decimal Apply(decimal total);
}

public class VipDiscount : IDiscountStrategy
{
    public decimal Apply(decimal total) => total * 0.90m;
}