Defensive Programming
https://www.joyent.com/node-js/production/design/errors (opens in a new tab)
assert vs exception
https://stackoverflow.com/questions/409794/exception-vs-assert (opens in a new tab)
Assert:
- programmer error (due to incompetence)
- eliminate bugs
- when you know cannot happen
Exception:
- operational error
- handle bad data
- when out of normal program control flow (e.g. bad IO, out of memory etc)
Use case
https://www.npmjs.com/package/tiny-invariant (opens in a new tab)
why??
- readability
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");
// vs
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");- easy to remove error message in release build
Fail fast vs fail early
Offensive programming
https://www.martinfowler.com/ieeeSoftware/failFast.pdf (opens in a new tab)