Video in progress
Explain the Open/Closed principle with a practical example.
Code should be open for extension and closed for modification: adding a new capability should mean adding a new class, without editing classes that already work and are tested. You usually do this with interfaces and polymorphism.
📖 Answer
The broken case: the switch grows with every new payment type:
long fee(String type, long amount) {
switch (type) {
case "CARD": return amount * 1 / 100;
case "CLICK": return amount * 2 / 100;
// every time, we add something here...
default: throw new IllegalArgumentException(type);
}
}
The OCP-friendly version:
interface FeePolicy {
boolean supports(String type);
long fee(long amount);
}
class CardFee implements FeePolicy { ... }
class ClickFee implements FeePolicy { ... }
class FeeCalculator {
private final List<FeePolicy> policies;
FeeCalculator(List<FeePolicy> policies) { this.policies = policies; }
long fee(String type, long amount) {
return policies.stream()
.filter(p -> p.supports(type))
.findFirst()
.orElseThrow()
.fee(amount);
}
}
Now adding Uzcard is one new class. In Spring, if you ask for a List<FeePolicy> in the constructor, all the beans are collected automatically.
But don't push OCP everywhere in advance. Introduce the abstraction only when a second or third variant appears, otherwise you violate YAGNI.
Sign up to mark studied questions and save your progress.