Middle
What does the principle of openness/closedness mean?
sobes.tech AI
Answer from AI
Modules should be open for extension but closed for modification. This means that new functionality can be added without changing existing code. Achieved through the use of abstractions (interfaces, protocols, abstract classes) and inheritance.
Example: there is a PaymentProcessor protocol and implementations for different payment systems. A new payment system is added without modifying existing implementations.
protocol PaymentProcessor {
func processPayment(amount: Double)
}
class StripePaymentProcessor: PaymentProcessor {
func processPayment(amount: Double) {
// Stripe payment logic
print("Processing \(amount) via Stripe")
}
}
class PayPalPaymentProcessor: PaymentProcessor {
func processPayment(amount: Double) {
// PayPal payment logic
print("Processing \(amount) via PayPal")
}
}
// Adding a new system without changing existing classes
class ApplePayPaymentProcessor: PaymentProcessor {
func processPayment(amount: Double) {
// Apple Pay payment logic
print("Processing \(amount) via Apple Pay")
}
}
class PaymentManager {
private let processor: PaymentProcessor
init(processor: PaymentProcessor) {
self.processor = processor
}
func makePayment(amount: Double) {
processor.processPayment(amount: amount)
}
}
// Usage
let stripeManager = PaymentManager(processor: StripePaymentProcessor())
stripeManager.makePayment(amount: 100.0)
let applePayManager = PaymentManager(processor: ApplePayPaymentProcessor())
applePayManager.makePayment(amount: 50.0)