Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defensive programming in node.js using asserts

Considering that sometimes error messages in node are particularly unhelpful I like to liberally use asserts in my functions so that programming errors are caught asap and I can get a message which in general pinpoints the problem.

function doSomething(arg1, arg2){
  assert(!arg1, "arg1 is undefined");
  assert(!arg2, "arg2 is undefined");
  assert(!arg1.expectedFn, "arg1 does not have expectedFn");

  arg1.expectedFn(function(blah){
    ...
  }
}

Is this a particularly bad thing to do in node/javascript programs? Does this have an impact on performance?

like image 437
Moiz Raja Avatar asked Nov 02 '12 16:11

Moiz Raja


1 Answers

(this is more of an opinion than fact post, so take it for what it's worth)

Asserts definitely do nothing good for performance, but used in moderation I doubt they have a serious enough of an impact to matter. That said, generally speaking good test coverage is preferable to asserts whenever possible. Also, what asserts you do write should not be redundant to what errors will naturally be thrown at runtime, unless they are particularly opaque.

Let's consider a modified (and somewhat contrived) version of doSomething -

function doSomething(arg1, arg2){
  var res = arg1.expectedFn(function(blah){
    ...
  }
  return res + arg2;
}

I would argue there's no point in checking arg1 for existence or it contains a function name expectedFn. If either are undefined, the javascript runtime will throw a fairly understandable TypeError that will say exactly what happened; the asserts are redundant.

However, you may find it desirable to test arg2 here. Suppose it's undefined, and res is a string or number - you'd then end up with "undefined" appended to the string, or NaN returned. Both are fairly subtle errors that can exist for a long time without anyone noticing - if you want it to fail sooner rather than later for debugging purposes, then you may want to add a few asserts to ensure it's the correct type.

In general, if you're concerned about rigor, I believe that energy would be better put to use in writing comprehensive tests: writing tests that fully cover the cases when doSomething is called will likely lead to a better, more robust development process than asserts. There are a few cases where asserts are appropriate, but they're limited to cases where malformed results can exist for a long time without any direct errors, but still able to cause undesirable side effects.

like image 89
Bubbles Avatar answered Oct 02 '22 19:10

Bubbles