Question

Within the context of JavaScript/Node.JS; Will using Callback functions improve the maintainability of source code, when there is no need for async programming?

For example does the plain code sound semantically more correct and will be easier to maintain/extend, rather than the second one that unnecessarily uses callback functions?

Plain

var validateId = function ( id ) {

    if ( undefined !== id ) {
        return true;
    } else {
        return false;
    }
}

var setId = function ( id ) {

    if ( true === validateId(id) ) {
        userId = id;
        console.log( "success" );
    } else {
        console.log( "failed: ", "invalid id" );
    };
}

Callback-ed

var validateId = function ( id, success, fail ) {

    if ( undefined !== id ) {
        success( id );
    } else {
        fail( "invalid id" );
    }
}

var setId = function ( id ) {

    validateId( id, function success (validatedId) {
        userId = validatedId;
        console.log( "success" );
    }, function fail ( error ) {
        console.log( "failed: ", error );
    });
}

Update #1

I'm not looking for a general advise on how to write readable and maintainable code. As written in the first line, I'm specifically looking to see if using Callbacks (not even in any programming languages, but specifically in JavaScript) will improve the maintainability of the code? And if that makes the source code semantically more correct? (invoke validateId and if the result was true set the userId comparing to invoke validateId and assign the userId on success)

Was it helpful?

Solution

Both solutions can make sense. Using functions as parameters is useful in many cases, and this generally makes it easier to write correct code because you're forced to provide callbacks for all circumstances. However, an API that requires callbacks tend to create unnecessarily deep indentation. This becomes more obvious when we have more than one validation, and all must pass:

// simple solution
function validateA(a) { return a !== undefined }
function validateB(b) { return b !== undefined }
function validateC(c) { return c !== undefined }

function frobnicate(a, b, c) {
  if (! validateA(a)) {
    console.log("failed: ", "invalid a");
    return;
  }
  if (! validateB(b)) {
    console.log("failed: ", "invalid b");
    return;
  }
  if (! validateC(c)) {
    console.log("failed: ", "invalid c");
    return;
  }
  console.log("success");
}
// naive callback solution
function validateA(a, onSuccess, onError) {
  return (a !== undefined) ? onSuccess(a) : onError("invalid a");
}
function validateB(b, onSuccess, onError) {
  return (b !== undefined) ? onSuccess(b) : onError("invalid b");
}
function validateC(c, onSuccess, onError) {
  return (c !== undefined) ? onSuccess(c) : onError("invalid c");
}

function frobnicate(a, b, c) {
  return validateA(a, function successA(a) {
    return validateB(b, function successB(b) {
      return validateC(c, function successC(c) {
        console.log("success");
      }, function failC(msg) { console.log("failed: ", msg) });
    }, function failB(msg) { console.log("failed: ", msg) });
  }, function failA(msg) { console.log("failed: ", msg) });
}

With this callback-based validation, control flow is incomprehensible, and because the success handler comes before the error handler, error handling is visually separated from the problem it's handling. This is a hindrance to maintenance. Simply slapping callbacks on functions doesn't scale.

Patterns do exist to solve this. For example, we could write a combinator that takes care of correctly composing the callback-based validation functions:

function multipleValidations(validations, onSuccess) {
   function compose(i) {
     if (i >= validations.length) {
       return onSuccess;
     }
     var cont = compose(i + 1);
     var what       = validations[i][0];
     var validation = validations[i][1];
     var onError    = validations[i][2] || function(msg) {};
     return function(x) { return validation(what, cont, onError) };
  }
  return compose(0)();
}

function frobnicate(a, b, c) {
  return multipleValidations([
    [a, validateA, function failA(msg) { console.log("fail: ", msg) }],
    [b, validateB, function failB(msg) { console.log("fail: ", msg) }],
    [c, validateC, function failC(msg) { console.log("fail: ", msg) }]
  ], function success() {
    console.log("success");
  });
}

Well, it's now much nicer to use validation, but the multipleValidations helper is ugly (and non-obvious, and difficult to maintain). That same interface would have been much easier to implement if each validation was just a predicate which returns a boolean (except that now the validation can't define the error message itself, and must depend on the error callback instead):

function multipleValidations(validations, onSuccess) {
   for (var i = 0; i < validations.length; i++) {
     var what     = validations[i][0];
     var validate = validations[i][1];
     var onError  = validations[i][2] || function fail() {};
     if (! validate(what)) {
       return onError();
     }
   }
   return onSuccess();
}

Using callbacks where they are not required is not only a KISS violation (keep it simple and stupid). They sometimes actively get in the way and obfuscate code. Some patterns do require callbacks, and using them there is OK.

Another reason why we should prefer the simpler solution is that we can easily transform both representations of validation into each other:

function predicateToCallback(predicate, errorMessage) {
  return function validate(x, onSuccess, onError) {
    return (predicate(x)) ? onSuccess(x) : onError(errorMessage);
  };
}

function callbackToPredicate(validate) {
  return function predicate(x) {
    return validate(x, function onSuccess() {
      return true;
    }, function onError() {
      return false;
    });
  };
}

In your original code, the callback-based solution does not return a value, so transforming a callback into a predicate becomes marginally more difficult:

function callbackToPredicate(validate) {
  return function predicate(x) {
    val result;
    validate(x, function onSuccess() {
      result = true;
    }, function onError() {
      result = false;
    });
    return result;
  };
}

Because it is so simple to transform one representation of the same concept into the other one, we ought to start out with the more simple one. If for some reason needed, the callback based solution is just a function call away. But quite likely, you ain't gonna need it (YAGNI).

Licensed under: CC-BY-SA with attribution
scroll top