🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Defensive Interfaces

A defensive interface is a function boundary that checks its inputs before doing work. Bad inputs are refused with a clear error.

An assert stops a broken rule

21 passes the check and doubles to 42. A negative input fails the check and prints a fixed message.

function double_positive(x)
    @assert x > 0
    return 2 * x
end
println(double_positive(21))
try
    double_positive(-3)
catch
    println("bad input")
end

An argument check refuses a bad value

A count of 1 returns the first item. A count of 0 is refused with a fixed message.

function take_first(items, n)
    if n < 1
        throw(ArgumentError("bad"))
    end
    return items[1]
end
println(take_first([10, 20], 1))
try
    take_first([10, 20], 0)
catch
    println("rejected")
end

Both checks can guard one function

80 passes both checks. A value above 100 is refused with a fixed message.

function score_level(score)
    @assert score >= 0
    if score > 100
        throw(ArgumentError("high"))
    end
    return score
end
println(score_level(80))
try
    score_level(120)
catch
    println("rejected")
end

Example

function register(age)
    @assert age >= 0
    if age > 120
        throw(ArgumentError("high"))
    end
    return age
end
println(register(30))
try
    register(200)
catch
    println("rejected")
end
try
    register(-1)
catch
    println("rejected")
end

Key points

  • Precondition: a rule an input must meet before the work starts.
  • Assert: @assert checks a rule and stops the code when the rule fails.
  • ArgumentError: an error thrown when an argument value is not allowed.
  • Catch: a failed check is caught so the code can print a fixed message.
  • Fixed message: a plain message the code prints, never the caught error itself.

In this example, register accepts 30 and prints it. It refuses 200 with ArgumentError and refuses -1 with a failed assert, and each refusal prints the fixed message rejected.

Note

@assert is for rules the caller must never break, while ArgumentError marks a bad value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

A function has @assert x > 0. It is called with -3 inside a try block. What prints if the catch block prints "bad input"?