Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

The Open/Closed Principle: What it is and why it matters

March 22, 2023

The Open/Closed Principle: What it is and why it matters

The Open/Closed Principle is one of the fundamental principles in object-oriented programming. It was coined by Bertrand Meyer and is part of the SOLID principles. The principle states that a software entity (class, module, function, etc.) should be open for extension but closed for modification. In simpler terms, it should be possible to extend the behavior of a system without modifying its source code.

Why it matters

This principle matters because it promotes maintainability, reusability, and robustness in software design. By adhering to the Open/Closed Principle, developers can make changes to the system without altering existing code, reducing the risk of introducing new bugs and preserving the stability of the original system.

Example in C

Let’s consider a simple example in C to demonstrate the Open/Closed Principle. Suppose we have a Shape interface with a method calculateArea that calculates the area of different shapes. We have two concrete classes Circle and Rectangle that implement the Shape interface.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Shape interface
typedef struct {
    double (*calculateArea)(void* self);
} Shape;

// Circle
typedef struct {
    Shape shape;
    double radius;
} Circle;

// Rectangle
typedef struct {
    Shape shape;
    double width;
    double height;
} Rectangle;

// calculateArea method for Circle
double circleCalculateArea(void* self) {
    Circle* circle = (Circle*)self;
    return 3.14 * circle->radius * circle->radius;
}

// calculateArea method for Rectangle
double rectangleCalculateArea(void* self) {
    Rectangle* rectangle = (Rectangle*)self;
    return rectangle->width * rectangle->height;
}

int main() {
    Circle circle;
    circle.shape.calculateArea = &circleCalculateArea;
    circle.radius = 5.0;

    Rectangle rectangle;
    rectangle.shape.calculateArea = &rectangleCalculateArea;
    rectangle.width = 4.0;
    rectangle.height = 6.0;

    double circleArea = circle.shape.calculateArea(&circle);
    double rectangleArea = rectangle.shape.calculateArea(&rectangle);

    // Use the area values as needed
    // ...
}

In this example, the Shape interface is open for extension as new shapes can be added by implementing the interface without modifying existing code. The calculateArea method is closed for modification, as adding a new shape does not require changing the existing implementation.

Example in Python

Now, let’s see how the Open/Closed Principle can be applied in Python using classes and inheritance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from abc import ABC, abstractmethod

# Shape interface
class Shape(ABC):
    @abstractmethod
    def calculateArea(self):
        pass

# Circle
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def calculateArea(self):
        return 3.14 * self.radius * self.radius

# Rectangle
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def calculateArea(self):
        return self.width * self.height

# Usage
circle = Circle(5.0)
rectangle = Rectangle(4.0, 6.0)

circleArea = circle.calculateArea()
rectangleArea = rectangle.calculateArea()

# Use the area values as needed
# ...

In this Python example, the Shape interface is open for extension, as new shapes can be added by creating new classes that derive from the Shape base class. The calculateArea method is closed for modification, as adding new shapes does not require changing the existing implementation.

Conclusion

In conclusion, the Open/Closed Principle promotes modular, flexible, and scalable software design by allowing for easy extension and minimal modification. By applying this principle, developers can build systems that are easier to maintain, test, and extend, leading to more robust and adaptable software.

Remember, while it’s important to understand and apply these principles, it’s equally essential to strike a balance and not over-engineer code to adhere strictly to a principle. Always consider the specific needs and requirements of the project at hand when making design decisions.

I hope this blog post has helped you understand the Open/Closed Principle and its significance in object-oriented programming! Happy coding!


➡️ Refactoring techniques for cleaner code


⬅️ Check if a directory exists in python


Go back to Posts.