Junior — Middle
How can you ensure that a system module is open for extension but closed for modification?
sobes.tech AI
Answer from AI
To make a system module open for extension but closed for modification, the Open/Closed Principle from SOLID is applied.
This is achieved by:
- Using abstractions (interfaces, abstract classes) that define the behavior of the module.
- Implementing new functionalities through inheritance or composition without changing the original module code.
- Applying design patterns, such as Strategy or Decorator, which allow adding behavior dynamically.
Example in Dart (Flutter):
abstract class PaymentProcessor {
void pay(double amount);
}
class CreditCardProcessor implements PaymentProcessor {
@override
void pay(double amount) {
print('Payment of $amount using credit card');
}
}
class PayPalProcessor implements PaymentProcessor {
@override
void pay(double amount) {
print('Payment of $amount via PayPal');
}
}
// The module uses the abstraction PaymentProcessor and can be extended with new payment methods without changing existing code.