DesignTheSystem/dev
Code Design (LLD) 6 min read

Polymorphism at scale

Give each kind of thing its own class when the behaviour really differs.

When types differ in behaviour

Chess pieces all answer "where can I move?" but each answers differently. One switch on the piece letter grows into hundreds of lines. An abstract Piece with one subclass per kind keeps each rule small.

abstract class Piece {
  abstract targets(board: Board, from: Square): Square[];
  protected slide(board: Board, from: Square, dirs: Dir[]) { /* shared */ }
}
class Rook extends Piece {
  targets(b: Board, f: Square) { return this.slide(b, f, STRAIGHT); }
}

Share through helpers

Common steps (sliding until blocked, jumping by offsets) go in the base class as protected helpers. Subclasses stay one or two lines.

Key takeaways

  • Different behaviour per kind: one class per kind.
  • Shared steps go in base-class helpers.
  • Map input to classes once, at the edge.

Hands-on coding exercise

Shapes report their own area. totalArea adds them up without asking what kind each one is, so a new shape needs no change to it.

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private readonly r: number) {}
  area(): number {
    throw new Error("Not implemented");
  }
}

class Rectangle implements Shape {
  constructor(private readonly w: number, private readonly h: number) {}
  area(): number {
    throw new Error("Not implemented");
  }
}

function totalArea(shapes: Shape[]): number {
  throw new Error("Not implemented");
}

Run your solution against 4 automated tests in the interactive workspace:

Check your understanding

Answer these questions interactively to test what you learned and track progress on your skill map:

  1. Where should the table from letters ("N", "Q") to piece classes live?
  2. Rook, Bishop and Queen all slide. How do you avoid repeating it?

Continue learning