Junior — Middle
Which SOLID principle concerns the openness and closedness of software modules for changes?
sobes.tech AI
Answer from AI
The SOLID principle related to the openness and closedness of software modules for changes is called the Open/Closed Principle (OCP). It states that software entities (classes, modules, functions) should be open for extension but closed for modification. This means that the behavior of a module can be extended without changing its source code, which increases the robustness and maintainability of the code.
Example in C++:
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() {}
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override { return width * height; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
// Now you can add new shapes without changing existing code