3 ms·
Eh, it's a matter of opinion here. Personally, I like the explicit statement that EITHER all of this OR ELSE all of that will happen: if (x < 0) {
by ubertaco 11y ago
Eh, it's a matter of opinion here.
Personally, I like the explicit statement that EITHER all of this OR ELSE all of that will happen:
if (x < 0) {
throw new Exception("Nonnegative numbers only!");
} else {
return 10 ** x;
}
This reads clearly: if x is less than zero, then throw a new exception; otherwise (that is, "or else"), return 10 to the xth power.
The other nice part about this is that it guards against the case where in the future I decide to have my "guard clause" log an error some other way instead of throwing an exception...and forget to ensure that my guard clause exits the function cleanly. Consider this snippet in your proposed style:
if (x < 0) {
throw new Exception("Nonnegative numbers only!");
}
return 10 ** x;
If I were to later change this to:
if (x < 0) {
logger.error("Nonnegative numbers only!");
}
return 10 ** x;
I now have to remember to go back in and add a return or something in my guard clause to make sure that the rest of the function doesn't execute.
Yes, this example is perhaps contrived, but I find every little bit of safeguarding to reduce cognitive overhead helps. :)
Ideally, I think, a type system that could help me out here would be useful (so that I could express my function as accepting a nonnegative number rather than just accepting a number), or else operation contracts of some kind for the method so that I don't have to manually sanity-check my input, but almost no languages have such features (at least, as of yet).