Using Facebook invariant vs. throw

I looked at various sources of Node.js projects, and I noticed that some people use invariant . From what I understood, invariant is a tool that allows you to put statements in your code and raise errors if necessary.

Question:

When would you prefer to use invariant against metal bugs in the traditional way?

 // Using invariant function doSomething(a, b) { invariant(a > b, 'A should be greater than B'); } // If throw function doSomething(a, b) { if(a <= b) { throw new Error('A should be greater than B'); } } 
+7
javascript error-handling invariants
source share
1 answer

There are several reasons:

  • Easier to read when you want to stack them. If you have, say, 3 prerequisites for verification, you always see invariant(x ... , and it is easy to see that it is 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 throwing method:

 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"); } 

  • This makes it easy to fix it in release builds.

    It often happens that you want preconditions to be checked in dev / test, but you don't want them to be released due to how slow they are. If you have such an invariant function, you can use a tool like babel (or some other) to remove these calls from production assemblies (this is similar to how D does it).

+11
source share

All Articles