solid open closed principle example c#

Mastering SOLID: Open-Closed Principle in C# Examples

By James Lopez
AD

The SOLID principles are fundamental object-oriented design guidelines that help software developers create more stable and maintainable applications. The Solid Open Closed Principle (SOCP) is one of these principles, prescribing that software entities should be open for extension but closed for modification. In other words, you should design your modules so they can be extended without altering their source code. Let's explore this principle with practical examples in C#.

SOCP is crucial for preventing subclass pollution, where a class takes too many responsibilities due to being open for modification. Instead, we aim to keep our classes focused on their core responsibilities and allow them to be extended through specialized behaviors.

Understanding Open and Closed Aspects

The open-closed principle can be comprehended by looking at its two key aspects: open for extension and closed for modification.

AD
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
open×close
open×close
Open-close
Open-close

Being closed for modification implies that the behavior of a class should not be changed once it has been implemented. We achieve this by using abstract classes, interfaces, and base classes that cannot be directly instantiated. This ensures that the existing implementation is stable and won't be affected by future changes.

Indicators of Closed-for-Modification Design

Developing classes with a solid understanding of when to stop modifying and start extending is essential for SoCP. The following are common indicators of closed-for-modification design:

Open and Closed Class Words in English | Definition | Examples | Differences
Open and Closed Class Words in English | Definition | Examples | Differences
Open and close worksheet | Learning Opposites | for kids
Open and close worksheet | Learning Opposites | for kids
SOLID Principles Explained: A Visual Guide to Better System Design
SOLID Principles Explained: A Visual Guide to Better System Design
  • Using the sealed keyword to prevent inheritance.
  • Creating abstract classes or methods that define an abstraction but don't provide an implementation.
  • Defining interfaces that outline the behavior expected of implemented classes.

Implementing these indicators ensures that existing code won't be disrupted by further modifications to the class hierarchy.

Examples of Closed Designs in C#

Let's consider an example of an abstract Shape class in C#. To calculate the area of a shape, we'd create specialized classes for each shape, such as Circle and Rectangle, without modifying the Shape base class.

AD
```csharp public abstract class Shape { public abstract double Area { get; } } ```

Here, the Shape class is closed for modification, as no implementation for the Area property is provided. Instead, the Area property is abstract and must be implemented by any derived class.

Open and Closed Shapes Worksheets
Open and Closed Shapes Worksheets
open×close
open×close
an open circuit and closed circuit are shown in this diagram
an open circuit and closed circuit are shown in this diagram
Preschoolers Worksheets
Preschoolers Worksheets
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 Close Worksheet | Behaviour Therapy
Open Close Worksheet | Behaviour Therapy

Now, let's create concrete implementations of the Circle and Rectangle classes:

```csharp public class Circle : Shape { private readonly double radius; public Circle(double radius) { this.radius = radius; } public override double Area => Math.PI * Math.Pow(radius, 2); } public class Rectangle : Shape { private readonly double width; private readonly double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public override double Area => width * height; } ```

In the above examples, the Shape class remains closed for modification, while allowing developers to extend its functionality through the implementation of specialized shapes.

AD

Adding New Functionality: Open for Extension

Being open for extension means that new functionality can be added without altering the existing classes' source code. This is accomplished by creating separate configurable modules that can be easily extended by plugging in new implementations.

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
Open & Closed Syllable Door Puzzle - FREE PRINTABLES
Open & Closed Syllable Door Puzzle - FREE PRINTABLES
Open / Close
Open / Close
Understanding SOLID Principles: A Guide for Developers
Understanding SOLID Principles: A Guide for Developers
an image of various objects that can be used to draw
an image of various objects that can be used to draw
Facebook
Facebook
there are many different types of closing tools in this page to learn how to open the door
there are many different types of closing tools in this page to learn how to open the door
Open - Close.
Open - Close.
an open box and a closed box are shown in two separate pictures, each with different boxes
an open box and a closed box are shown in two separate pictures, each with different boxes
SOLID Principle in Programming: Understand With Real Life Examples
SOLID Principle in Programming: Understand With Real Life Examples
the open and closed styles worksheet for students to practice their english language skills
the open and closed styles worksheet for students to practice their english language skills
Close vs Shut vs Cover vs Seal | Everyday English Vocabulary
Close vs Shut vs Cover vs Seal | Everyday English Vocabulary
an open and closed window with polka dots
an open and closed window with polka dots
Противоположные слова с закрытой и открытой иллюстрацией | Бесплатный вектор
Противоположные слова с закрытой и открытой иллюстрацией | Бесплатный вектор

As an example, let's enhance our Shape classes to include different coloring methods. Instead of adding a new coloring method directly to our existing Shape class, we'll create an interface called IShapeColorer that defines how a shape can be colored. This way, we can add new coloring methods without modifying the original Shape class.

Examples of Open-Extension Design in C#

Here's how we can define the IShapeColorer interface and implement it using different coloring strategies:

AD
```csharp public interface IShapeColorer { void ColorShape(Shape shape); } public class SolidColorer : IShapeColorer { private readonly Color fillColor; public SolidColorer(Color fillColor) { this.fillColor = fillColor; } public void ColorShape(Shape shape) { // Implementation to color shape with a solid color } } public class GradientColorer : IShapeColorer { private readonly Gradient gradient; public GradientColorer(Gradient gradient) { this.gradient = gradient; } public void ColorShape(Shape shape) { // Implementation to apply a gradient to the shape } } ```

By designing our classes to be open for extension, we've allowed developers to introduce new coloring methods without modifying the original Shape class. This promotes an easy and maintainable way to add new functionality to our existing codebase.

In conclusion, understanding and applying the Solid Open Closed Principle is essential for creating robust, maintainable software that is resistance to changes and easy to extend. By closed for modification and open for extension, we can keep our codebase stable while allowing for future growth. By following these principles, your C# applications will be more adaptable and better prepared to face the challenges of an ever-evolving development landscape.

AD