Facebookの不変条件とif throwの使用 質問する

Facebookの不変条件とif throwの使用 質問する

様々なNode.jsプロジェクトのソースを見てきましたが、一部の人が不変私が理解したところによると、invariantこれはコードにアサーションを挿入し、必要に応じてエラーを発生させることができるツールです。

質問:

invariant従来の方法でエラーをスローするのではなく、を使用することを好むのはどのような場合ですか?

// 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');
   }
}

ベストアンサー1

理由はいくつかあります:

  • 積み重ねると読みやすくなります。たとえば、検証する前提条件が 3 つある場合は、常に が表示されinvariant(x ...、何がチェックされているかが簡単にわかります。

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

通常のスローアプローチと比較してください。

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

  • リリースビルドで簡単に排除できるようになります。

    多くの場合、前提条件は開発/テストでチェックする必要がありますが、リリースでは遅くなるためチェックしたくない場合があります。そのような関数がある場合は、invariantbabel (または他のツール) などのツールを使用して、これらの呼び出しを製品ビルドから削除できます (これは、D のやり方に似ています)。

おすすめ記事