Video in progress
What does it mean when instanceof checks pile up in a row in your code, and how do you rewrite it?
Usually it means polymorphism isn't being used: the behavior lives in an outside if chain instead of in the objects themselves. Every time a new type is added, you have to find and edit all such chains. The fix is to move the method to the common type, or use a full switch over a sealed hierarchy.
📖 Answer
The problematic code:
long shippingCost(Parcel p) {
if (p instanceof Letter) return 5_000;
if (p instanceof Box b) return 15_000 + b.weightKg() * 2_000;
if (p instanceof Pallet pl) return 200_000;
throw new IllegalArgumentException("Noma'lum tur");
}
If a new Envelope type is added, the compiler says nothing, and the bug only shows up at runtime.
Option 1 is classic polymorphism. The behavior moves into the object:
interface Parcel { long shippingCost(); }
record Letter() implements Parcel { public long shippingCost() { return 5_000; } }
record Box(int weightKg) implements Parcel {
public long shippingCost() { return 15_000 + weightKg * 2_000L; }
}
Option 2 is sealed + a pattern matching switch (Java 21). Use it if you want to keep the calculation logic outside the domain objects (for example, in a separate service):
sealed interface Parcel permits Letter, Box, Pallet {}
long cost = switch (parcel) {
case Letter l -> 5_000;
case Box b -> 15_000 + b.weightKg() * 2_000L;
case Pallet p -> 200_000;
};
Here, if a new type is added, the compiler gives an error.
Which to choose: if types are added often and operations are few, option 1. If the types are stable and there are many operations (price, tax, export), option 2 is more convenient.
Sign up to mark studied questions and save your progress.