Callback functions: Semantics and maintainability, when they aren’t necessary [duplicate]

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)

2

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).

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Callback functions: Semantics and maintainability, when they aren’t necessary [duplicate]

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)

2

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).

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật