I have an if/else if structure that on some cases does nothing. From the code I have seen in my career, the "empty" case is normally left out. But when I wrote my code, it just doesn't feel right to leave this case out, but to show it as a real case that simply does nothing. For example, in a case where something is done when a number is below 5 and above 10, but in between nothing is done:

int a = 4
if(a < 5) {
  do something
} else if(a >=5 && a <= 10) {
  // do nothing
} else if(a > 10) {
  do something else
}

The reason I thought this is a better option is because:

  1. The is how I though about the problem in my mind.
  2. This shows the reader of the code that I thought of all the possibilities and didn't forget one by mistake.

So I was wondering if this convention is either accepted by the programming community or it is shunned upon.

有帮助吗?

解决方案

You are not simply checking the value of a for the sake of it. It probably means something.

Thus I would prefer to see:

Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = a >= 5 & a <= 10;
// or even: 
Boolean error = !sell & !buy;
/* ^ (that's single source principle: if 5 changes to 6 one day, 
 * you don't have to remember to change it in two places) */

And then:

if (sell) {

} else if (buy) {

} else if (error) {

}

Isn't it clearer?

Furthermore, could a be both less than 5 and greater than 10??

Rather not, so those elses are clearly redundant. (Unless you change the value of a within one of your if blocks, mind you, If you only evaluate a once, however - as in my example - you don't have to worry about it).

Hence:

Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = !sell & !buy;

if (sell) {

} 
if (buy) {

} 
if (error) {
    // handle error
}

This is way clearer and more flexible in my opinion - if some conditions are no longer mutually exclusive, as it can happen, you won't need to do much refactoring at all.

其他提示

I would avoid to define the do nothing case explicit by giving the intervall. I would use an else-branch for that

int a = 4
if(a < 5) {
  do something
} else if(a > 10) {
  do something else
} else {
     //This should mean: (a >=5 && a <= 10)
     // do nothing

     // Maybe log something here 
     // or even add an assertion while development to ensure that the 
     // branch is only reached in expected cases:
     assert (a >=5 && a <= 10) : "I expected 'a' to be 5<=a<=10, but a is:"+a;
}
许可以下: CC-BY-SA归因
scroll top