Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Clean Code60 XP6 min

Logic & Polymorphism

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

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.

πŸ”§ Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it β€” it helps us fix it fast.

Hint: G22: Inject dependencies; never silently rely on globals. G23: Add a virtual method to the base class instead of a new switch branch.

βœ— Your version

Logic & Polymorphism β€” CleanKata β€” CleanKata