Parse, don't validate

I think there’s already a lot that you can do in the spirit of “parse, don’t validate” using Julia’s type system. Of course what you end up with when there are bugs is MethodErrors instead of static compilation errors.

One thing that I sometimes forget is that if I’m writing code that processes data that I’ve created myself inside my program, then I don’t need to validate it, since I’m the one who created it and I know what shape it’s in. :slight_smile:

So I think the advice in “parse, don’t validate” is focused mostly on processing input data. But some of the advice applies generally, like this one:

Use a data structure that makes illegal states unrepresentable.

Sometimes you see a function like this:

function foo(; flag1, flag2)
    if flag1 && flag2
        1
    elseif flag1 && !flag2
        2
    elseif !flag1 && flag2
        3
    else
        error("flag1 and flag2 cannot both be false")
    end
end        

But you could just make the 4th state illegal by using the type system:

# Hopefully there are more natural names that you can use
# in your real application.
struct Flag1Flag2 end
struct Flag1NotFlag2 end
struct NotFlag1Flag2 end

foo(::Flag1Flag2)    = 1
foo(::Flag1NotFlag2) = 2
foo(::NotFlag1Flag2) = 3
5 Likes