Junior — Middle
Can you explain the main idea of the open-closed principle in object-oriented programming?
sobes.tech AI
Answer from AI
The Open/Closed Principle in object-oriented programming means 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. Such an approach helps avoid errors that can occur when modifying tested code and makes maintenance and development easier.
For example, if you need to add new functionality, it is better to create a new class that extends the existing one rather than changing the original class directly.
Example in Swift:
protocol Shape {
func area() -> Double
}
class Circle: Shape {
var radius: Double
init(radius: Double) { self.radius = radius }
func area() -> Double { return .pi * radius * radius }
}
class Rectangle: Shape {
var width: Double, height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
func area() -> Double { return width * height }
}
// To add a new shape, for example Triangle, we do not change existing classes, but create a new one:
class Triangle: Shape {
var base: Double, height: Double
init(base: Double, height: Double) {
self.base = base
self.height = height
}
func area() -> Double { return 0.5 * base * height }
}