How to avoid code duplication when defining a function with multiple methods?

So instead of

function f(x::Int, y::Int)
    println("This code is called every time.")
    println("Doing stuff to integer: ", x)
    println("Doing stuff to integer: ", y)
end

function f(x::Float64, y::Int)
    println("This code is called every time.")
    println("Doing stuff to float: ", x)
    println("Doing stuff to integer: ", y)
end

...

You do

function f(x, y)
    println("This code is called every time.")
    dostuff(x)
    dostuff(y)
end

dostuff(x::Int) = println("Doing stuff to integer: ",  x)
dostuff(x::Float64) = println ("Doing stuff to float: ", x)
...
3 Likes