As the topic states, sometimes these issues conflict. For example...
In this case, the nominal case is first, but the expression is n开发者_如何学JAVAegative.
if ( !foo.IsDead() ) {
DoThis();
} else {
DoThat();
}
In this case, the expression is positive, but the nominal case is last.
if ( foo.IsDead() ) {
DoThat();
} else {
DoThis();
}
Of course, a third option would be to flip around the IsDead function to be IsAlive(). I'd like to hear others' thoughts on these 3 choices when they encounter them in coding. Do you go with nominal, positive, or fix the whole thing by flipping the boolean itself.
I prefer option two as it's slightly clearer / easier to read.
But you're heading for religious war territory I suspect.
In terms of flipping the name of the function, I'd only change if isAlive() is the most likely outcome. That is, I think the code is clearer if the most likely outcome is your boolean expression equating to true. The least likely (false) should come second. It it's 50/50 then I wouldn't worry.
What are you going to check for more - being alive
or dead
. If the scale tilts significantly towards one of them, you should name the predicate method accordingly.
As for placing nominal or positive cases first, I'd go with the nominal. It's not that hard to figure out !dead
as being alive or vice versa, but it's always nice to see the main flow of execution first and the exceptional cases later.
When arranging the if statements, I put them in order of frequency if I know it at all. This surely improves performance.
When dealing with code that checks for error and then progress accordingly, I always put the error handling code in the last if statement. This contributes to code readability.
Regarding your 3rd option, I only make sure that the method name itself is not negative such as isNotAlive(), otherwise I take it just fine.
You may want to read Section 15.1 (if Statements) of Code Complete. This section discusses about an almost similar issue.
I think it depends on what the frequency of interaction is. In general I was taught that you should always put the most frequent, or most likely case as the true evaluation for the if case, and put supsequent ones in the else block. I think it is a matter of personal choice though.
I don't like something like this..
if ( IsDead() ){}
else
{
//do something.
}
so I would prefer the former.
精彩评论