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:
- The is how I though about the problem in my mind.
- 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.
Best Answer
You are not simply checking the value of
a
for the sake of it. It probably means something.Thus I would prefer to see:
And then:
Isn't it clearer?
Furthermore, could
a
be both less than5
and greater than10
??Rather not, so those
else
s are clearly redundant. (Unless you change the value ofa
within one of yourif
blocks, mind you, If you only evaluatea
once, however - as in my example - you don't have to worry about it).Hence:
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.