I have function with data and callback parameters. The data is an object with many attributes and I have to validate these. I wrote multiple if, else if statements to do it, but it seems so disgusting to me.
function(data, callback) {
if (data.a != 'x') {
logger.log(...);
return callback({status: false, code: 'x'});
} else if (data.b != 'y') {
logger.log(...);
return callback({status: false, code: 'y'});
} else if (data.c != 'z') {
logger.log(...);
return callback({status: false, code: 'z'});
} else if (data.d != 'w') {
logger.log(...);
return callback({status: false, code: 'w'});
}
//... logic ...
return callback({status: true});
}
I think It's not the appropriate way to do it.
One way would be to factor the validation into a separate function:
function failureCode(data) {
if (data.a != 'x')
return 'x';
if (data.b != 'y')
return 'y';
if (data.c != 'z')
return 'z';
}
function (data, callback) {
var code = failureCode(data);
if (code) {
logger.log(...);
return callback({status: false, code: code});
}
//... logic ...
}
Also, don't forget to return from the "failed" branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With