In our last lesson, we explored the Single Responsibility Principle (SRP), which guides us to create focused classes, each with a single reason to change. This is the first step toward a clean design. Now, a new question arises: once we have these well-defined classes, how do we add new functionality to our application without modifying the existing, tested code?
This lesson addresses that exact question by introducing the second SOLID principle: the Open/Closed Principle (OCP). Your goal is to understand this principle so you can explain it clearly in your interview and demonstrate its application with a C# example. OCP is a cornerstone of building scalable and maintainable software, as it allows a system to evolve without compromising its stability.
1. Defining the Open/Closed Principle
At its heart, the Open/Closed Principle provides a clear directive for managing change in software. The formal definition, coined by Bertrand Meyer, is:
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
This might sound like a paradox. How can something be both open and closed? Let's break it down:
- Open for Extension: This means the behavior of a module or class can be extended. As new business requirements emerge, we should be able to add new functionality to the system.
- Closed for Modification: This means the source code of an existing, working module or class should not be changed. Once a class has been developed, tested, and deployed, we should avoid altering it, as that risks introducing bugs into functionality that was previously stable.
The following video provides an excellent summary of these two concepts and why this principle is so important.
Solid Principles Full Tutorial In C# - Interview Answers - Design Patterns In .NET - Coding Examples
This segment from SECourses on YouTube clearly explains the meaning behind "open for extension" and "closed for modification," and outlines the problems that arise when OCP is ignored.
Watch the portion of the video from the initial definition up to the discussion of the interview question. Pay close attention to the distinction between adding new responsibilities via extension versus modifying an existing class.
2. Spotting an OCP Violation
Violations of OCP are very common in codebases and are often easy to spot. They typically appear as if-else if chains or switch statements that check the type of an object or an enum value to determine which logic to execute.
Consider the following C# code that calculates a discount based on the type of invoice.

The problem here is clear: the GetInvoiceDiscount method is not closed for modification. If the business decides to add a new invoice type, say RecurringInvoice, a developer must go into this method and add another else if block. This modification requires:
- Changing a class that was previously working correctly.
- Re-testing the entire
GetInvoiceDiscountmethod to ensure existing cases (FinalInvoice,ProposedInvoice) were not accidentally broken. - Potentially violating SRP, as the method's responsibility grows with each new invoice type.
This situation is brittle and doesn't scale well. The core logic becomes a central point of frequent changes, increasing the risk of bugs.
To see another common example of this problem, let's look at a banking scenario.
Open Closed Principle in SOLID
This article from C-Sharp Corner presents another classic OCP violation.
Read the section titled "Example of not following the principle in Application Development". Notice how the CalculateInterest method suffers from the exact same problem as the GetInvoiceDiscount method in our previous example.
3. Refactoring to Adhere to OCP
The key to satisfying the Open/Closed Principle is abstraction. Instead of depending on concrete implementations, our code should depend on interfaces or abstract base classes. This allows us to introduce new functionality by creating new classes that conform to the abstraction, rather than modifying the old ones.
There are two primary patterns to achieve this in C#:
- Using Interfaces: Define an interface that represents the contract for the behavior. Each new concrete class implements this interface.
- Using Inheritance: Define an
abstractbase class with anabstractorvirtualmethod. Each new concrete class inherits from the base and provides its own implementation (override).
The following video is a fantastic, practical demonstration of refactoring a C# application that violates OCP into one that follows it using interfaces. It perfectly illustrates the thought process an engineer would go through.
Design Patterns: Open Closed Principle Explained Practically in C# (The O in SOLID)
In this detailed video, Tim Corey walks through a real-world scenario of evolving an application, first showing how OCP is violated and then refactoring the code to fix it. This is an excellent deep dive into the "how" and "why."
First, watch the segment demonstrating the problem. Observe how adding new employee types (Manager, Executive) forces repeated modifications to the central account creation logic, leading to a complex switch statement and even introducing a bug. Next, watch the segment that implements the solution using interfaces. The presenter refactors the code to depend on IApplicantModel and IAccounts interfaces. See how this allows him to add new ManagerModel and ManagerAccounts classes without touching the original Accounts class at all. This is the core of OCP in action.
As the video demonstrates, by programming to an interface, the system becomes "pluggable." The main loop that creates accounts now works with any object that implements the IApplicantModel interface. It doesn't know or care whether it's a PersonModel, ManagerModel, or ExecutiveModel. We can add a TechnicianModel tomorrow by simply creating a new class; no existing code needs to change.
While interfaces are often preferred for their flexibility, using an abstract base class is another powerful technique. It's particularly useful when you want to share some common implementation among all subclasses.
Top 6 SOLID Principles C# Interview Questions with code - DotNetInterviews
This resource from DotNetInterviews provides a very concise example of OCP using an abstract base class.
Focus on question 3, "What is the Open/Closed Principle (OCP)?". The Shape example shows how you can create a calculator that can find the area of various shapes. To add a new shape, like a Triangle, you simply create a new Triangle class that inherits from Shape. The calculator code, which works with Shape objects, doesn't need to be modified.
How to Explain OCP in an Interview
If you are asked to explain the Open/Closed Principle, here is a clear structure for your answer:
- Definition: Start with the formal definition. "The Open/Closed Principle states that software entities should be open for extension but closed for modification."
- Elaboration: Explain what this means in practical terms. "It means we should be able to add new functionality to a system without changing existing, tested code. This minimizes the risk of introducing new bugs into stable parts of the application."
- Example (The Problem): Describe a violation. "A classic violation is a method with a large
switchstatement that checks an object's type. For instance, a functionCalculateDiscount(Invoice invoice)that uses a switch oninvoice.Type. Every time a new invoice type is added, this function has to be modified." - Example (The Solution): Explain the fix using abstraction. "To fix this, we'd apply OCP by creating an
IInvoiceinterface with aCalculateDiscount()method. We would then create separate classes for each invoice type, likeFinalInvoiceandProposedInvoice, each implementing theIInvoiceinterface. The client code would then work with theIInvoiceinterface, and we could add new invoice types just by creating new classes, without ever touching the client code." - Benefits: Conclude with the advantages. "Following OCP results in a system that is more maintainable, stable, and robust. It promotes a 'pluggable' architecture where new features can be added with minimal impact on the existing codebase."
Conclusion
The Open/Closed Principle is a crucial guideline for building software that can adapt to change. By leveraging abstraction through interfaces and inheritance, you can design systems that are both extensible and stable. This moves you from writing code that simply works today to engineering systems that are built to last.
Key Takeaways:
- OCP: Software should be open for extension but closed for modification.
- The Problem: Avoid modifying existing, tested code to add new features. Watch out for
if/elseorswitchstatements based on type. - The Solution: Use abstractions like interfaces or abstract base classes. Introduce new functionality by creating new classes that implement or inherit from these abstractions.
- The Benefit: Your system becomes more robust, maintainable, and easier to extend over time.
In our previous lesson on SRP, we learned to break down classes. Now, with OCP, we've learned how to structure them to allow for extension. But what rules govern these extensions? Our next lesson will cover the Liskov Substitution Principle (LSP), which provides the rules for creating correct and substitutable subclasses, ensuring that our abstractions hold true.