Sobes.tech
Middle

What is the open/closed principle (OCP)?

sobes.tech AI

Answer from AI

The Open/Closed Principle (OCP) is one of the five SOLID principles, which states that software entities (classes, modules, functions) should be open for extension but closed for modification.

This means that the behavior of a system can be extended without changing existing code, which increases robustness and ease of maintenance.

For example, if you need to add new functionality, it is better to create a new class that implements the required interface or inherits from a base class rather than modifying existing code.

Example in Swift:

protocol Shape {
    func area() -> Double
}

class Circle: Shape {
    var radius: Double
    init(radius: Double) {
        self.radius = radius
    }
    func area() -> Double {
        return Double.pi * radius * radius
    }
}

class Rectangle: Shape {
    var width: Double
    var height: Double
    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
    func area() -> Double {
        return width * height
    }
}

// If you need to add a new shape type, create a new class without changing existing ones
class Triangle: Shape {
    var base: Double
    var height: Double
    init(base: Double, height: Double) {
        self.base = base
        self.height = height
    }
    func area() -> Double {
        return 0.5 * base * height
    }
}

Thus, the code is open for extension (new shapes) but closed for modification of existing classes.

What is the open/closed principle (OCP)? — iOS - sobes.tech