Junior — Middle
Kas saaksite selgitada objektiivse programmeerimise avamise ja sulgemise põhimõtte põhiteooriat?
sobes.tech AI
Vastus AI-lt
The Open/Closed Principle in object-oriented programming 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. This approach helps to 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 directly changing the original class.
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, do not modify 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 }
}