🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Dispatch Design

Dispatch design is the shaping of methods so a function stays clear as it grows. A good design gives each method one job and keeps the common cases easy to read.

A general method covers the rest

The general method handles text. The special method handles whole numbers.

label(x) = "general"
label(x::Int) = "whole"
println(label("hi"))
println(label(5))

One name can offer several choices

One name offers two size choices. Each call prints its own price.

price(::Val{:small}) = 5
price(::Val{:large}) = 9
println(price(Val(:small)))
println(price(Val(:large)))

A new case leaves old calls unchanged

Two methods exist at first. A new method for decimals leaves the old call unchanged.

tag(x::Int) = "whole"
tag(x::String) = "text"
println(tag(5))
tag(x::Float64) = "decimal"
println(tag(5))
println(tag(2.5))

Example

tag(x::Int) = "whole"
tag(x::String) = "text"
println(tag(5))
tag(x::Float64) = "decimal"
println(tag(5))
println(tag(2.5))
println(length(methods(tag)))

Key points

  • Interface: the set of methods a caller can use is the interface of a function.
  • One job: each method should handle one clear case.
  • General method: a broad method covers cases with no special method.
  • Special method: a narrow method handles one case in its own way.
  • Most specific wins: Julia picks the most specific matching method, not the first method written.

In this example, two methods exist at first. A call prints whole. A new method for decimals is added. The old call still prints whole, the new call prints decimal, and the count prints three.

Note

a new method for a new case should leave old calls unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

You add a method for a new case to a function. What should happen to old calls?