I have built RESTful web services. The services endpoints have a similar logic:
- If the input validation succeeds, do a database operation and return the result.
- If the db operation fails, return the db error.
- If the validation fails, return a response with information on the failed validation.
My code was explicit in the sense you can read the code and understand the flow of the program. A coworker refactored it so that this basic flow is refactored in a utility class which main function takes the request body, the db operation and the handlers. Now the code doesn't express the flow but the basic logic is refactored.
Which code better follows best practice? Would you sacrifice readability for refactoring? Yes, the unit test will be reduced a bit too.
Example:
Before:
save: function (req, res, next) {
var dao = topicsDaoFactory.create(req.dbSession);
validate(req.body.topic, constraintsObj,
function success () {
dao.save(req.body.topic, function saveHandler (err, result) {
if (err) {
res.error(err);
} else {
res.send(result);
}
});
},
function error (errors) {
res.fail(errors);
});
}
After:
save: function (req, res) {
var dao = topicsDaoFactory.create(req.dbSession);
ControllerUtils.validateAndTryOperation(req, res, {
input: req.body.topic,
constraints: constraintsObj,
operation: function (input, callback) {
dao.create(Topic.createFromScratch(input), callback);
}
});
}
next
parameter for? \$\endgroup\$ – 200_success Sep 22 '15 at 5:51