I recently tend to design my methods in the following way:
if ( 'A' === $a ) {
if ( 'B' === $b ) {
return 'some thing';
} else if ( 'C' === $c ) {
return 'some other things';
}
}
/* If you made it up to here, then something has gone wrong */
return false;
So basically the idea is to check if the first condition is correct, if it is then continue until you reach the first return
statement to return the expected result, if not, move on to the next condition and so on.
The key is that all the method's functionality has already shrunken down and wrapped up in a conditional statement piece by piece, so you should meet at least one condition to take a useful action or if you reach the very last line, then it will return false
, that means none of the expected conditions were met, that in my design it means the input wasn't in a proper or expected format, data-type, range, etc. so the method were not able to continue processing that.
I can achieve the same goal in a couple of different ways, but this one seems to be cleaner as I generally need to write code only for positive conditions (I actually don't know how should I call it) -- unless I need to take a specific action if a certain condition haven't met. And in the end I will get false
if the method wasn't able to accomplish its job -- with real conditions in place most of the time it's almost like a jump to the end of method when you can't pass through an if
statement. It's actually designed in a way that you will either pass this if
and will heading to the either next if
or a return
statement or you are very unlikely to match any other if
statements and will jump directly to the last return false
statement.
Now, my questions are:
- Is it a (true) fail-fast design, which in this case is only looking for the proper condition to continue and is willing to fail as soon as one fails. Is that correct or am I mixing up things here? If not, is there any specific term for that?
- Also as I recently generalized this approach for all the new methods I create, I wish to know if there is any drawback or design flaw here that might bite me back later.