SOLID & Design Patterns Interview Question #5

Give a practical example of an Open/Closed Principle violation.

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

Quick Interview Answer

A long switch statement that must be edited every time a new payment type is added can violate OCP when payment behavior is expected to grow. Each new type changes an existing central class.

Detailed Explanation

A long switch statement that must be edited every time a new payment type is added can violate OCP when payment behavior is expected to grow. Each new type changes an existing central class.

A better design can define a payment abstraction and add separate implementations for card, bank transfer, or other payment methods.

Code Example

public interface IPaymentProcessor
{
    Task ProcessAsync(decimal amount);
}

public class CardPaymentProcessor : IPaymentProcessor
{
    public Task ProcessAsync(decimal amount)
        => Task.CompletedTask;
}