Search code examples
node.jsassertassertions

Node.js: should I keep `assert()`s in production code?


A methodological question:

I'm implementing an API interface to some services, using node.js, mongodb and express.js.

On many (almost all) sites I see code like this:

method(function(err, data) {
  assert.equal(null, err);
});

The question is: should I keep assert statements in my code at production time (at least for 'low significance' errors)? Or, are these just for testing code, and I should better handle all errors each time?


Solution

  • You definitively should not keep them in the production environment.

    If you google a bit, there are a plethora of alternative approaches to strip out them.

    Personally, I'd use the null object pattern by implementing two wrappers in a separate file: the former maps its method directly to the one exported by the module assert, the latter offers empty functions and nothing more.

    Thus, at runtime, you can plug in the right one by relying on some global variable previously correctly set, like process.env.mode. Within your files, you'll have only to import the above mentioned module and use it instead of using directly assert.

    This way, all around your code you'll never see error-prone stuff like myAssert && myAssert(cond), instead you'll have ever a cleaner and safer myAssert(cond) statement.

    It follows a brief example:

    // myassert.js
    var assert = require('assert');
    if('production' === process.env.mode) {
        var nil = function() { };
        module.exports = {
            equal = nil;
            notEqual = nil;
            // all the other functions
        };
    } else {
        // a wrapper like that one helps in not polluting the exported object
        module.exports = {
            equal = function(actual, expected, message) {
                assert.equal(actual, expected, message);
            },
            notEqual = function(actual, expected, message) {
                assert.notEqual(actual, expected, message);
            },
            // all the other functions
        }
    }
    
    
    // another_file.js
    var assert = require('path_to_myassert/myassert');
    // ... your code
    assert(true, false);
    // ... go on