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:

Exception:

Use case

https://www.npmjs.com/package/tiny-invariant (opens in a new tab)

why??

  1. 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");
  1. 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)