open closed principle ocp example c#

Mastering the Open-Closed Principle in C#: OCP Code Examples

By Matthew Rodriguez
AD

The Open-Closed Principle (OCP), introduced by SOLID principles-governor Robert C. Martin, is a fundamental concept in software design that emphasizes designing modules to be open for extension but closed for modification. This ensures that new functionality can be introduced without altering existing code. Let's delve into OCP with examples in C#.

Imagine a baking scenario: Our base class represents a cake, and its method, `Bake()`. Anyone can create a new cake by extending this base, but once it's baked, we don't change the original recipe. This encapsulates OCP's essence.

Understanding OCP in C#

The OCP example in C# involves interface segregation and dependency injection.

AD
Open and Closed Class Words in English | Definition | Examples | Differences
Open and Closed Class Words in English | Definition | Examples | Differences
Open vs closed questions
Open vs closed questions
Open and close worksheet | Learning Opposites | for kids
Open and close worksheet | Learning Opposites | for kids

Consider an abstract class `IShape` with methods `CalculateArea()` and `Draw()`. Now, an ellipse implementing this might have `_radius` instead of a width and height, making `Draw` less applicable. To respect OCP, we'd better this to separate interfaces `IDrawable` and `IAreaCalculable`.

Interface segregation and OCP

Segregating the `IShape` interface into `IDrawable` and `IAreaCalculable` adheres to OCP:

Open-close
Open-close
Nikki Siapno on LinkedIn: SOLID principles explained in under 2 minutes: Whether or not you use… ...
Nikki Siapno on LinkedIn: SOLID principles explained in under 2 minutes: Whether or not you use… ...
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+

`IDrawable`: // This allows us to draw only shapes which can be drawn. `IAreaCalculable`: // Then, shapes which calculate area.

Thus, we maintain existing behavior but extend functionality without changing original code.

AD

Dependency Injection (DI) and OCP

Another C# method to apply OCP is through DI. It inverts relationships between classes for loose coupling, which makes code more testable and maintainable.

open×close
open×close
Open and Closed Shapes Worksheets
Open and Closed Shapes Worksheets
Preschoolers Worksheets
Preschoolers Worksheets
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
Open-Ended and Close-Ended Questions
Open-Ended and Close-Ended Questions
Monday Minute: Open vs. Closed Composition - Art Terms Explained | LittleArtTalks
Monday Minute: Open vs. Closed Composition - Art Terms Explained | LittleArtTalks

Here's a simple DI example where `IVehicle` is an interface for the `Vehicle` class. `GasolineEngine` and `ElectricEngine` implement `IVehicle` methods:

In `Vehicle class`: ```csharp public abstract class Vehicle { protected IVehicleEngine engine; public Vehicle(IVehicleEngine engine) { this.engine = engine; } public void Start() { engine.Start(); } } ```

Now, you can easily swap engines, respecting OCP by being open for extension but closed for modification.

Practical OCP Examples in C#

Let's explore a real-life example of applying OCP to a logging system.

Assume we have a base class `LogManager` that handles logging mechanism. Now, we develop this logging system to support both file logging and database logging.

File Logging

The `FileLogManager` extends `LogManager`, providing the `LogToFile()` method to write logs to a file.

Database Logging

Similarly, `DatabaseLogManager` extends `LogManager`, using ADO.NET for database logging. We apply OCP here by allowing new logging targets (like an API or a monitoring system) without modifying `LogManager`.

The power of OCP lies in making our system adaptable to new changes without breaking existing parts. This is a key aspect of maintainable and extendable software. In the vast landscape of C#, OCP is a guiding light to design versatile and robust code.

So, as we conclude, remember to embrace OCP principles in your next C# project, making your codebase flexible and robust, ready for the future. Happy coding!

Teaching & Learning
Teaching & Learning
Open cloze exercise
Open cloze exercise
Maker, designer, and engineer Matt Harrison (aka "Quintox303") over at Thingiverse has created a clever 3D printed open and closed sign design that can Open And Close, Flipping Sign Board, Open Closed Sign 3d, Open Close Sign Design, Kinetic Door Mechanism, Understanding Linkage Mechanisms, Open Closed Sign Svg, Open Sign Close-up, Reversible Open Closed Sign
Maker, designer, and engineer Matt Harrison (aka "Quintox303") over at Thingiverse has created a clever 3D printed open and closed sign design that can Open And Close, Flipping Sign Board, Open Closed Sign 3d, Open Close Sign Design, Kinetic Door Mechanism, Understanding Linkage Mechanisms, Open Closed Sign Svg, Open Sign Close-up, Reversible Open Closed Sign
SOLID Principles Explained: A Visual Guide to Better System Design
SOLID Principles Explained: A Visual Guide to Better System Design
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
an open / closed sign with the words pringle ocf
an open / closed sign with the words pringle ocf
Object-Oriented Software Principles
Object-Oriented Software Principles
Open close interactive worksheet
Open close interactive worksheet
an open closed pringle diagram with several different types of words and numbers on it
an open closed pringle diagram with several different types of words and numbers on it
Educational Postcard: Open vs. Closed Learning
Educational Postcard: Open vs. Closed Learning
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
the instructions for how to open mailbox
the instructions for how to open mailbox
AD