open closed principle example c#

Mastering Open-Closed Principle in C#: Real-World Examples

By Christopher Taylor
AD

The Open Closed Principle (OCP) is a fundamental concept in software engineering, advocating for the design of entities so that they can be open for extension but closed for modification. This principle, proposed by Bertrand Meyer, promotes modularity and reusability, allowing developers to extend a class's behavior without altering its source code. Let's explore this concept with examples in C#.

In C#, we can exemplify the Open Closed Principle using interfaces and polymorphism, enabling us to add new functionality without modifying existing code. Thisversammlung is particularly useful in runtime scenarios where you want to avoid breaking changes during an update.

The Interface Segregation Principle And OCP

The Interface Segregation Principle (ISP) complements OCP by promoting client-specific interfaces. This reduces the dependency between classes, making them more cohesive and improving code maintainability.

AD
Open and Closed Class Words in English | Definition | Examples | Differences
Open and Closed Class Words in English | Definition | Examples | Differences
Open-close
Open-close
four different pictures with the words open, closed, and in front of an open door
four different pictures with the words open, closed, and in front of an open door

In C#, we can implement ISP by creating small, targeted interfaces that clients can easily implement, and reassembling these interfaces to form more comprehensive behavior.

ISpImplementation: Creating Small Interfaces

Consider a logging system with different logging levels (DEBUG, INFO, WARN, ERROR). Instead of creating a single interface with all methods (LogDebug, LogInfo, LogWarn, LogError), we create an interface for each level:

Open close
Open close
open×close
open×close
Preschoolers Worksheets
Preschoolers Worksheets
```csharp public interface IDebugLogger { void LogDebug(string message); } public interface IInfoLogger { void LogInfo(string message); } public interface IWarnLogger { void LogWarn(string message); } public interface IErrorLogger { void LogError(string message); } ```

Now, each logger implementation only needs to implement the required interfaces:

```csharp public class ConsoleLogger : IInfoLogger, IWarnLogger { public void LogInfo(string message) { Console.WriteLine($"INFO: {message}"); } public void LogWarn(string message) { Console.WriteLine($"WARN: {message}"); } } ```

Polymorphism: Extending Behavior Without Modification

Polymorphism enables adding new functionality without altering existing code. In C#, we can achieve this using method overriding or interface implementation.

AD

Suppose we have a base logger service that accepts an ILogger interface:

Open and Closed Shapes Worksheets
Open and Closed Shapes Worksheets
Open and close worksheet | Learning Opposites | for kids
Open and close worksheet | Learning Opposites | for kids
an open and closed umbrella next to two small houses with the words open close above them
an open and closed umbrella next to two small houses with the words open close above them
Open Mind vs Closed Mind | Powerful Life Lesson Illustration
Open Mind vs Closed Mind | Powerful Life Lesson Illustration
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
```csharp public abstract class LoggerService { public void Log(ILogger logger, LogLevel level, string message) { switch (level) { case LogLevel.DEBUG: logger.LogDebug(message); break; // ... default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } } } ```

Now, to extend the logging functionality, we simply create a new logger interface and class without altering the base service:

```csharp public interface ITraceLogger { void LogTrace(string message); } public class TraceLogger : IInfoLogger, ITraceLogger { public void LogTrace(string message) { Console.WriteLine($"TRACE: {message}"); } // ... } ```

Adding the new trace logging functionality doesn't require modifying the base logger service, adhering to the Open Closed Principle. This demonstrates the advantage of using interfaces and polymorphism to extend functionality without disruptive changes.

AD

Open Closed Principle In Unit Testing

The Open Closed Principle also comes into play in unit testing, promoting code that is easy to test without altering its internals. This encourages modular design and loose coupling, making your code more maintainable and testable.

two boys in open and closed boxes with balls on white background stock photo - image
two boys in open and closed boxes with balls on white background stock photo - image
two signs showing how to open and close clothes
two signs showing how to open and close clothes
Open & Closed Syllable Door Puzzle - FREE PRINTABLES
Open & Closed Syllable Door Puzzle - FREE PRINTABLES
Open-Ended and Close-Ended Questions
Open-Ended and Close-Ended Questions
Open minded vs closed minded
Open minded vs closed minded
an open and closed sign on white background
an open and closed sign on white background
Open close interactive worksheet
Open close interactive worksheet
Thingiverse - The community for Open Hardware
Thingiverse - The community for Open Hardware
two stickers with the words sorry we're closed and an open sign that says sorry
two stickers with the words sorry we're closed and an open sign that says sorry
the words closure are written in black and white, with arrows pointing to different directions
the words closure are written in black and white, with arrows pointing to different directions
Open and Close
Open and Close
an open sign on the side of a door that says open and two gears are attached to it
an open sign on the side of a door that says open and two gears are attached to it

In C#, you can apply OCP in unit tests using dependency injection and interfaces, enabling you to swap out implementations easily:

Dependency Injection: Swapping Out Implementations

Suppose you have a service that depends on a logger. Instead of directly using the concrete logger class, you can inject an interface through the service's constructor:

AD
```csharp public class MyService { private readonly ILogger _logger; public MyService(ILogger logger) { _logger = logger; } // ... } ```

Now, you can easily swap out the logging implementation for testing purposes. For example, you can use a logger that discards all logs (DoNothingLogger) during testing:

```csharp [Fact] public void Test_Something_DoesNotLog() { var logger = new DoNothingLogger(); var service = new MyService(logger); // Arrange, Act, Assert } ```

By applying the Open Closed Principle, you ensure that your code is flexible, modular, and easy to extend and test, ultimately resulting in a more maintainable and reusable codebase.

In conclusion, following the Open Closed Principle in C# development brings numerous benefits, such as better maintainability, extensibility, and testability. By utilizing interfaces, polymorphism, and dependency injection, you can create a more flexible, modular, and resilient code structure that stands the test of time and change.

AD