I'll Be Backend
Principles · TypeScript

Inheritance: pull up duplicated behavior

Write shared behavior once in a superclass, so every subclass gets each change.

10 steps4 chapters~4 min at 1.25×#oop#inheritance#duplicated code#superclass
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the TypeScript video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–6

Payoff

Steps 7–8

Recap

Steps 9–10

The code: before and after

Before

abstract class Shipment {
  abstract price(): number;
}

class DomesticShipment extends Shipment {
  private readonly tracking: string;
  private readonly weightKg: number;

  constructor(tracking: string, weightKg: number) {
    super();
    this.tracking = tracking;
    this.weightKg = weightKg;
  }

  price(): number {
    return 5 + this.weightKg;
  }

  label(): string {
    const head = `${this.tracking} | ${this.weightKg} kg`;
    return `${head} | $${this.price()}`;
  }
}

class InternationalShipment extends Shipment {
  private readonly tracking: string;
  private readonly weightKg: number;

  constructor(tracking: string, weightKg: number) {
    super();
    this.tracking = tracking;
    this.weightKg = weightKg;
  }

  price(): number {
    return 20 + this.weightKg * 4;
  }

  label(): string {
    const head = `${this.tracking} | ${this.weightKg} kg`;
    return `${head} | $${this.price()}`;
  }
}

function dispatch(): string[] {
  const home = new DomesticShipment("DM-1", 2);
  const abroad = new InternationalShipment("IN-7", 2);
  return [
    home.label(), // DM-1 | 2 kg | $7
    abroad.label(), // IN-7 | 2 kg | $28
  ];
}

After

abstract class Shipment {
  protected readonly tracking: string;
  protected readonly weightKg: number;
  private fragile = false;

  constructor(tracking: string, weightKg: number) {
    this.tracking = tracking;
    this.weightKg = weightKg;
  }

  abstract price(): number;

  markFragile(): void {
    this.fragile = true;
  }

  label(): string {
    const head = `${this.tracking} | ${this.weightKg} kg`;
    const suffix = this.fragile ? " | FRAGILE" : "";
    return `${head} | $${this.price()}${suffix}`;
  }
}

class DomesticShipment extends Shipment {
  price(): number {
    return 5 + this.weightKg;
  }
}

class InternationalShipment extends Shipment {
  price(): number {
    return 20 + this.weightKg * 4;
  }
}

function dispatch(): string[] {
  const home = new DomesticShipment("DM-1", 2);
  const abroad = new InternationalShipment("IN-7", 2);
  abroad.markFragile();
  return [
    home.label(), // DM-1 | 2 kg | $7
    abroad.label(), // IN-7 | 2 kg | $28 | FRAGILE
  ];
}

Transcript, step by step

Problem

Step 1: A courier's two shipments Before

A parcel courier's dispatch desk works with two kinds of shipment. Shipment is the superclass, the class the others extend, and each subclass, a class that extends it, says what its parcel costs. Both subclasses also keep a tracking code and a weight, and both build a label from them. The dispatch function builds one domestic parcel and one international one, and returns both labels.

Step 2: Fragile parcels Code smell

The courier now needs the word fragile on the label of fragile parcels. The quick way adds a fragile field, a mark fragile method and a label suffix to Domestic Shipment, and then the same three again to International Shipment. Dispatch marks the parcel going abroad, so only the second label ends in fragile.

Step 3: Two copies of everything Code smell

Duplicated code across subclasses is when two classes that share a superclass each write the same fields and methods on their own. You can see the fields here and here, and the label here and here. So every change to the label is made twice, and the day someone edits only one copy, a fragile parcel ships without the word on it. A third shipment type would copy all of it a third time.

Refactor

Step 4: Refactor first Back it out

Let's take the fragile flag out again. We'll refactor first, so that the shared parts move up into Shipment, and then we'll add the flag in one place.

Step 5: One constructor Pull Up Constructor Body

In strict TypeScript, a field must be assigned in the constructor of the class that declares it, so the fields and the constructor body move up together. Shipment's constructor now assigns the tracking code and the weight once, and both fields stay read only. The two subclass constructors only passed their arguments along to super, so both are deleted, and each subclass inherits the constructor of Shipment. Dispatch still builds both parcels with a tracking code and a weight, and gets the same two labels.

Step 6: One label Pull Up Method

Now the two label bodies are identical, so one copy moves up into Shipment, and both subclass copies are deleted. Label still works because it calls price, and each subclass still answers price its own way. This is inheritance, where a subclass gets the fields and methods of its superclass, so the shared parts are written once, in Shipment. What's left in each subclass is its price. A superclass method that calls a step each subclass fills in, like label calling price, is the Template Method pattern.

Payoff

Step 7: Fragile, once Add the flag

Now the fragile flag comes back, and this time it goes into Shipment only. Shipment gains one fragile field and one mark fragile method, and label adds the suffix once. Domestic and International Shipment didn't change, and dispatch only gains one call that marks the parcel going abroad.

Step 8: Shared code lives once Payoff

The fields now exist once, here, and the label exists once, here. The fragile rule is written once too, so the two labels can't drift apart, and the run marks only the parcel going abroad. It fits because both classes are shipments, each with a tracking code, a weight and a label, and only the price differs. Abstraction hid how a class stores its data, and inheritance shares what two classes both do.

Recap

Step 9: Where we started, where we ended Before / after

On the left, each subclass keeps its own fields, its own constructor body and its own label. On the right, Shipment holds the fields, the constructor, the fragile flag and the label, each written once. A subclass like Domestic Shipment keeps only its own price.

Step 10: When to reach for it Takeaways

Reach for it when two or more subclasses of one superclass repeat the same fields or the same method body. Skip it when two classes look alike today but will change for different reasons, because a superclass ties them together, so use Extract Class and delegate to it. You'll spot the need by the same method copied into sibling subclasses, and the same fields and constructor lines in each. The built-in Error class works this way, because a subclass with an empty body still inherits its constructor, the message and the stack.