There are a few reasons:
- It's easier to read when you want to stack them. If you have, say, 3 preconditions to validate, you always see
invariant(x ...
, and it's easy to see what's being checked:
function f(xs, x) {
// all the invariants are lined up, one after another
invariant(xs.type == x.type, "adding an element with the same type");
invariant(xs.length != LIST_MAX_SIZE, "the list isn't full");
invariant(fitting(x), "x is fitting right in the list");
}
Compare with the usual throw approach:
function f(xs, x) {
if (xs.type != x.type)
throw new Error("adding an element with the same type");
if (xs.length == LIST_MAX_SIZE)
throw new Error("the list isn't full");
if (!fitting(x))
throw new Error("x is fitting right in the list");
}
It makes it easy to eliminate it in release build.
It's often that you want preconditions checked in dev/test, but don't want them in release because of how slow they'd be.
If you have such an invariant
function, you can use a tool like babel (or some other) to remove these calls from production builds
(this is somewhat like how D does it).
Preconditions
in Google guava (Java)