Skip to the page

OOP and SOLID · core

Open-closed principle

Add new behaviour by adding new classes, not by editing old code. A payment method with an if/else for every type should become one handler class per type behind an interface, chosen from a registry.

The notes

What you must know

  • Every new type in an if/else chain edits and retests the whole method, and the class grows forever. String types also allow typos.
  • Define PaymentMethodHandler with type() and pay(request), and one class per type. This is the Strategy pattern.
  • Pick the handler from a registry: a map from PaymentType to handler, built from all handlers (in Spring, inject a List of handlers and index by type). Adding buy-now-pay-later is one new class.
  • Replacing if/else with a switch does not fix it. A giant switch to choose the handler is the same problem.
  • Shared steps (validation, fraud check, recording) stay in the orchestrator or in a template method, not copied into each handler.
  • Use an enum or a value object for the type, not a raw string. Do not put every new field in a shared Map of strings.
  • It is fine to keep a simple if for two stable cases that will never grow. Do not build plugins for that.

The red pen

Common traps: mistake → fix

  • Mistake: A switch statement is open-closed

    Fix: a switch still has to be edited for every new case.

  • Mistake: Open-closed means never touch old code

    Fix: you still edit wiring and config; the logic of old types stays unchanged.

  • Mistake: Always build the extension point

    Fix: build it where change is likely, not everywhere.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the open-closed principle? Give an example.
  2. Adding a payment type means editing old code. How do you fix it?
  3. How does a registry or factory help?
  4. When is an if/else good enough?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview