Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
This prevents issues introduced by changes to existing code.
This principle is often applied in object-oriented programming through the use of inheritance and polymorphism.
It allows us to add new functionality to a class without changing its existing code,
thus preventing bugs and making the code more maintainable.
For example, if we have a class that calculates the area of a shape, we can extend it to support new shapes
without modifying the existing code.
abstract class Shape {
abstract fun area(): Double
}
class Circle(private val radius: Double) : Shape() {
override fun area() = Math.PI * radius * radius
}
class Rectangle(private val width: Double, private val height: Double) : Shape() {
override fun area() = width * height
}
Here, the Shape
class is open for extension, as we can add new shapes by creating new classes that extend it.
However, it is closed for modification, as we do not need to change the existing code to add new shapes.