I'll Be Backend
Principles · Swift

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 Swift 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

class Shipment {
    func price() -> Int {
        fatalError("override price()")
    }
}

class DomesticShipment: Shipment {
    private let tracking: String
    private let weightKg: Int

    init(tracking: String, weightKg: Int) {
        self.tracking = tracking
        self.weightKg = weightKg
    }

    override func price() -> Int {
        5 + weightKg
    }

    func label() -> String {
        "\(tracking) | \(weightKg) kg | $\(price())"
    }
}

class InternationalShipment: Shipment {
    private let tracking: String
    private let weightKg: Int

    init(tracking: String, weightKg: Int) {
        self.tracking = tracking
        self.weightKg = weightKg
    }

    override func price() -> Int {
        20 + weightKg * 4
    }

    func label() -> String {
        "\(tracking) | \(weightKg) kg | $\(price())"
    }
}

let home = DomesticShipment(tracking: "DM-1", weightKg: 2)
let abroad = InternationalShipment(tracking: "IN-7", weightKg: 2)
print(home.label())    // DM-1 | 2 kg | $7
print(abroad.label())  // IN-7 | 2 kg | $28

After

class Shipment {
    let tracking: String
    let weightKg: Int
    private var fragile = false

    init(tracking: String, weightKg: Int) {
        self.tracking = tracking
        self.weightKg = weightKg
    }

    func price() -> Int {
        fatalError("override price()")
    }

    func markFragile() {
        fragile = true
    }

    func label() -> String {
        let base = "\(tracking) | \(weightKg) kg | $\(price())"
        return fragile ? base + " | FRAGILE" : base
    }
}

class DomesticShipment: Shipment {
    override func price() -> Int {
        5 + weightKg
    }
}

class InternationalShipment: Shipment {
    override func price() -> Int {
        20 + weightKg * 4
    }
}

let home = DomesticShipment(tracking: "DM-1", weightKg: 2)
let abroad = InternationalShipment(tracking: "IN-7", weightKg: 2)
abroad.markFragile()
print(home.label())    // DM-1 | 2 kg | $7
print(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, overrides price to say what its parcel costs. Both subclasses also keep a tracking code and a weight, set them in their own initializer, and build a label from them. The code at the bottom prints one label for a domestic parcel and one for an international one.

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 property, a mark fragile method and a label suffix to Domestic Shipment, and then the same three again to International Shipment. The run 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: Properties and init in Shipment Pull Up Constructor Body

In Swift a class must set its stored properties in its own initializer, so the fields and the initializer body move up together. Shipment now holds the tracking code and the weight once, and because Swift has no protected, they're plain lets that each subclass can read. Both subclass initializers are gone, because a Swift subclass that adds no stored properties inherits its superclass's initializer. The calls at the bottom still pass a tracking code and a weight, and print 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 property and one mark fragile method, and label adds the word once. Domestic and International Shipment didn't change, and the run 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 prints the word only on 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 declares its own fields, sets them in its own initializer and writes its own label. On the right, Shipment holds the fields, the initializer, the fragile flag and the label, each written once. A subclass like Domestic Shipment keeps only its own price, and inherits everything else.

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 properties and initializer lines in each. Foundation's Operation works this way, because a subclass overrides main, and inherits cancel, dependencies and queue handling.