Member-only story

That One Method Dispatch Pitfall

Can you avoid this?

Steven Curtis
3 min readFeb 19, 2023
Photo by George Pagan III on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Before tackling this article, you might want to look at my Method Dispatch Article

That tricky case

Any method defined inside a protocol is dynamically dispatched. This makes sense, since we do not know which method implementation will be used until runtime.

Both Mammal and Pig are Animal (stop me if this is too tricky!). Each makes a noise, which differs if they are in pain.

The code looks something like the following:

protocol Animal {
func animalSound(pain: Bool) -> String
}

class Mammal: Animal {
func animalSound(pain: Bool = false) -> String {
return "Indeterminate grunt \(pain ? "ttttt" : "")"
}
}

class Pig: Mammal {
override func animalSound(pain: Bool = true) -> String {
return "Oink \(pain ? "kkkk" : "")"
}
}

Those default arguments? They give a curious side-effect.

let mammal = Mammal()
mammal.animalSound() // "Indeterminate grunt"

The mammal isn’t in pain. That’s a good thing. However, we have simply created a mammal class which itself has the function animalSound and since our mammal isn’t in pain, it produces an…

--

--

No responses yet