5 ms·
This - if (!test()) { handle_failure(); } else { // do lots of work } is just another incarnation of if (NULL == v) i.e. it sacrifices a nat
by huhtenberg 14y ago
This -
if (!test()) {
handle_failure();
} else {
// do lots of work
}
is just another incarnation of
if (NULL == v)
i.e. it sacrifices a natural flow of code and makes it harder to follow for something of a superficial value.
Also this -
if (!test1()) {
handle_failure_1();
return false;
}
is fine unless the function needs to do a cleanup, which is pretty much always the case, and which in turn means that the { } block with grow with every if and it will include a lot of redundant code.
A far cleaner and easier to follow approach is to use if-goto, whereby all cleanup code sits at the bottom of the function (where it naturally belongs) and the flow jumps to the appropriate part of the cleanup on failure. The only exception is when there's no cleanup needed, in which case it can do if-return.
- dwc 14y agoI use both if-return and if-goto. In practice you need both, depending on circumstance. In much of my recent code I've managed to use a lot of if-return checks at the top of functions. Another nice thing about a bunch of if-returns at the beginning is it makes a nice checklist of things that will cause the function to fail, all right up front.
- huhtenberg 14y ago> a nice checklist of things that will cause the function to fail Should these be assert()s? ;)
- dwc 14y agoSometimes, yes.
- DeepDuh 14y agoNot sure if serious, but assert only makes sense in cases where you want to switch off the tests at some point right?
- huhtenberg 14y agoAsserts are for enforcing invariants in the code. If you replace an assert with a conditional that allows the execution to continue, you are concealing the problem and making it that much harder to track. Practically speaking, your function should not be failing because your other code passed it invalid parameters. That's a bug in the former. That's why parameter validity should be asserted.
- DeepDuh 14y agoI see. I usually never let execution continue and log + exit instead, but you're right, an assert is easier in that situation.
- yxhuvud 14y agoMakes sense. However, it was pretty well covered in the article as well.. Did you read the whole thing?
- huhtenberg 14y agoYes I did, and it is only mentioned in passing.