CSE Roadmap

Core tier · about 2 hours · 6 parts

Part 5 of 6 · 2 min read

Designing a small interface

Few methods, one idea, named for what it does.

Designing a small interface

An interface is a promise, and every extra method is a promise more. Habits that keep it small (common practice):

  • One idea. PaymentMethod has pay, not pay, refund, printReceipt and sendEmail. If a class does not need a method, it should not have to implement it. Level 2 names this as the interface segregation principle.
  • Name the role. PricingStrategy, Notifier, Clock. The name should say what the caller expects.
  • Hide the implementation. No method named after a mechanism, such as payByCardNumber.
  • Think of two implementations. If only one can ever exist, an interface may be extra cost. A test double also counts as a second implementation, which is a good reason for an interface at an edge such as a clock or a payment gateway.

A made-up count for the checkout above: 3 payment methods, 1 Checkout class. Without the interface, Checkout would have an if chain with three branches and must change for each new method. With it, Checkout has one line and each method is a separate, small class.

Interview angle

Answer in your head first, then open it.

What does "program to an interface" mean?

Declare and pass types as interfaces, and name concrete classes only where objects are created.

Interface or abstract class?

Prefer an interface for a type. Use an abstract class when implementations share real state or code.

What is the benefit?

New implementations can be added without changing the code that uses them.

Check yourself: 1. Why should PaymentMethod not have a printReceipt method? 2. What is a good name for an interface? 3. When is an interface for a single implementation justified?

Words you will meet

Word Meaning
Interface The requests an object can answer
Type The interface of an object
Class How an object is implemented
Interface inheritance One type can be used in place of another
Class inheritance One class's code is built on another's
Abstract class A class that cannot be instantiated and may leave methods open
Mixin An optional ability added by implementing an interface
Default method An interface method that carries code