Skip to the page

OOP and SOLID · mid

Interface segregation principle

Clients should not depend on methods they do not use. A fat PaymentMethod interface with refund, EMI and auto-pay forces cash on delivery to fill methods with exceptions. Split it by capability.

The notes

What you must know

  • A fat interface forces implementers to write methods that throw, and callers cannot trust the interface. This also breaks Liskov for callers.
  • Split by capability: PaymentMethod with pay, Refundable with refund, EmiCapable with createEmiPlan, AutoPayCapable with setupAutoPay. A card implements several, cash on delivery only the first.
  • Callers ask for the capability they need. The EMI flow takes an EmiCapable.
  • Adding a supportsEmi boolean to the fat interface is not a fix. Returning null is also not a fix.
  • Cash on delivery refunds probably happen another way (to a wallet or a bank), so that is a separate service, not a method that throws.
  • Balance: group methods that always change together. One method per interface is not the goal.
  • In other languages: Python protocols or abstract base classes, TypeScript interfaces.

The red pen

Common traps: mistake → fix

  • Mistake: More interfaces is always better

    Fix: splitting so far that every class implements eight interfaces is a problem too.

  • Mistake: A supportsEmi flag solves it

    Fix: callers still see methods they cannot use.

  • Mistake: Returning null from unsupported methods is safe

    Fix: callers crash later; make the type say what is supported.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the interface segregation principle?
  2. This PaymentMethod interface has six methods and COD throws on three. What do you do?
  3. How do the callers change after the split?
  4. How do you avoid splitting too much?

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