Skip to main content
Clean Code 60 XP · 6 min

Logic & Polymorphism

Make all dependencies explicit, and replace if/switch chains with polymorphic dispatch.

Showing
Ad (728×90)

Explicit Physical Dependencies

G22: If a function needs an environment variable, a configuration object, or a database handle, it should declare that dependency explicitly — not reach into a global or a static. Hidden dependencies make code unpredictable and hard to test. When a function's dependencies are explicit, you can substitute them in tests, and readers know exactly what the function needs to work.

Polymorphism Over Conditionals

G23: A switch statement that dispatches on an object's type is a code smell. Every time you add a new type, you must find and update every such switch. Polymorphism solves this by moving each branch into the class it belongs to. The area() method lives in Circle, Rectangle, and Triangle — not in a centralized switch. Adding a new shape means adding a new class, not editing existing code.

Code Challenge

Replace the compute_area switch with a polymorphic area() method on each shape.

Key takeaway

Every switch on type is a missed opportunity for polymorphism. Move the logic to the objects, not to the dispatcher.

Done with this lesson?

Mark it complete to earn XP and track your progress.