Many times, I'm writing a function which will return `true` on success and `false` on error/failure, and essentially wrapping another function which does the same.
An example (basically language-independent, but I'll write in ECMAScript for familiarity):
function SendEmail(to, from, subject, body) {
var eml = new EmailObj();
eml.To = to;
eml.From = from;
eml.Subject = subject;
eml.Body = body;
return eml.Send(); // This will return true/false
}
But, sometimes, I want to do something else depending on the result of the interior function (say log specific information):
function SendEmail(to, from, subject, body) {
var eml = new EmailObj();
eml.To = to;
eml.From = from;
eml.Subject = subject;
eml.Body = body;
if(!eml.Send()) {
Log("Error in send: " + eml.Response);
return false;
}
return true;
}
But, I never feel like I've written good code when I do something like that.
Would you write this differently? Am I being paranoid? Or do you think this pattern in and of itself leads to this dilemma and I should look to see if I can change the higher-level approach(es)?
以上就是Better way to code returning the result of a true/false call的详细内容,更多请关注web前端其它相关文章!