In many cases you have code like this (C-style pseudo code used):
bool checkCondition();
bool doSomething(){
if (checkCondition() == false)
return false;
// do something
return true;
}
I keep reusing this patter and every time wonder, if there is better way to express it?
Sometimes, the condition check can be left for the caller or asserted, but often condition check must be done inside the function.
You can get fancy and use exceptions, but result is almost the same code.
First I would express the negation like that:
Also I would prefer to have the positive condition in the if statement, whenever applicable (depending on the length of the blocks):
You could also drop the
elsehere because of a return in the `if``statement.