Best Practice: Default Values/Optional Arguments/Readable Code

This is more verbose, but it forces the default variable definition logic checks into the type inner constructor.

mutable struct RateVariables
    parameters::Dict{Symbol,Any}
    function RateVariables(p)
        # Enforce the default value if a parameter is missing
        category = get!(p, :risk_category, "AAA+") 
        horizon = get!(p,:years, 30)
        value = get!(p,:amount, 1000000)
        start = get!(p,:starting_date, 20190101)
        # Do anything else with the given & default values
        new(p) 
    end
end

# The all default values case
discount_rate(RateVariables(Dict()))

# Some parameters given:
# Note without {symbol, Any} passed to Dict you'll get a int -> string type conversion error when the
# string parameter is inserted
rv = RateVariables(Dict{Symbol,Any}( :years => 3, :amount=>1, :starting_date=>20000101))
discount_rate(rv)

Is it really so straightforward to say to a Julia newcomer:

If you want to use optional/default parameters, the simplest robust approach in Julia 1.x is to use a Dict, a mutable struct (aka type) and its inner constructor?

Appreciate any suggestions that are simpler.

1 Like