views:

317

answers:

9

In a situation where a variable could have two different values, and you do something if its one, something differnent if its the other, would you just do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else { ... }

or would you do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else if (myVariable == SECOND_POSSIBLE_VALUE) { ... }

for clarity, in a situation where a reader wouldn't necessarily be able to tell that they do the same thing (but the else if does a "needless" expression)? So what would you do? Thanks!

EDIT: There is actually about a lot more different options for something like this: ternary operator, if-else, if-elseif, if-elseif-else, -if-else(with assert), switch. Each one has its place, but its hard to decide..

+2  A: 

Else is a default. Meaning that there are either a large number of possibilities for the data, or that it is unexpected data.

I go by the basic rule: If there is a parameter that can be met, use else if, and if there isn't, use else. I normally use else's for errors.

Chacha102
A: 

It depends on the situation. Do you only want to take action if certain criteria are met, or is there a special case for one value and another set of logic for any other value?

Ed Swangren
+8  A: 

I always prefer just plain else when there is no other possible state of the variable(ie, checking for null and all that). I may add a comment saying what the variable is if it isn't the first conditional, but that is only in cases where its like

if(color==red){
....
}else{ //our theme only allows for red and yellow, so the color must be yellow.
....
}

Also, this saves some time for the processor cause it won't have to check a useless variable(or worse in OOP, where checking that variable can take quite a few dereferences, function calls, and memory reads)

I never do something like

if(file.is_open==1){
....
}else if(file.is_open==0){
....

}

as is_open is a boolean, it is pointless to specify that because the only option left is 0, also this can save a little bit of typing when you must refactor your code to use is_open() instead, as now you only must change one line instead of two.

and 'else if' statements I think should be turned to switches if there is more than 1 'else if', unless of course the language makes it impossible(such as how C can't handle strings in switches)

Earlz
It does certainly not make sense for boolean variables, but think of an integer result code. You always have the possibility to assign the return value to a local variable to save processor time.
Scoregraphic
+1  A: 

Sometimes the condition of the else statement is very obvious. For example

if(user.IsNew) { } else { /*in this case user.IsNew != true*/ }

But in some other cases the else isn't that obvious and it is better to clarify the else condition. This is also more future proof in case some other possible conditions are added.

Furthermore you are able to insert an exception in the (last) else to inform about unimplemented cases. This can be very useful when the for example backend and frontend are separated and somebody adds a new value to an enumerator (or when using text keys a new key is introduced) you will receive an error when the new value is first used. When not using if else if you won't see what happened and that could make debugging pretty hard.

if(user.SelectedStyle == Styles.Red) {
} else if(user.SelectedStyle == Styles.Basic) {
} else {
 throw new Exception("Not implemented");
}

In the case above a new Style (for example Style.Blue) will cause your application to throw an exception.

Gertjan
+1  A: 

It's really a matter of style and your own mental view of the world. The glass is BOTH half empty and half full, but you can get the darnedest arguments going about it.

If the boolean tests are all of the same type, a switch statement is best.

If not, I'd recommend leaving out the additional test but insert a comment about the operational meaning of falling through into that last statement. See Gertjan's comment, above.

Amagrammer
+2  A: 

I only use the if-else for boolean checks, that means that if the expression doesn't match there only can be the else. Or i want to take everything with the else: think of it like default.

If you want to check enumeration or something, you should try check this via switch statement, if possible in your language.

In Java it's not possible to use a switch for Strings. So you could use something like this:

if(string.equals("foo")) {
    // first case
} else if(string.equals("bar")) {
    // second case
} else {
    throw IllegalArgumentException(" ... ");
    // or log it
}

If you're not sure that your check can't be extended, you should if you can provide an default way.

codedevour
+1  A: 

Isn't this what assert was made for?

if (condition1) { ... }
else { assert(condition2); }

This can be expanded for three-state logic, too.

if (condition1) { ... }
elsif (condition2) { ... }
else { assert(condition3); }

Using assert makes your code readable, easy to maintain, and clear. That being said, asserts and comments are almost interchangeable.

Is asserting in the else any better than using else if?
Mk12
If you're assuming binary logic, like if (true) { ... } else { ... }, then using an assert will make any unexpected conditions go to the "base case". Typically, failing an assertion doesn't do much besides produce a warning, so your program would go ahead as normal. Whether or not this is desired is up to the programmer.
In my case (xcode), failing assertions stops the program and tells you the assertion failed.
Mk12
+1  A: 

When your input can be clearly separate into distinct cases, I feel it is mostly nicer to explicitly state what those cases are, for example if you are expecting 'n' to be a number between 0 and 100, and you have 3 cases:

if (n >= 0 && n < 30) {
   case1();
} else if (n >=30 && n < 70) {
   case2();
} else if (n >=70 && n < 100) {
   case3();
}

in some situations the 'else' case is good for error checking

} else {
   error("n should be between 0 and 100");
}

if your data is checked for erroneous values earlier, then there may be a case to use else for the final case, to provide a small performance improvement in languages like C:

} else { // (n >= 70 && n < 100)
   case3();
}

but this is only necessary due to some languages inability to express the domain of a function, in languages where the domain can be expressed clearly, the optimiser should add this performance benefit for you, allowing you to be specific in your code, and making it easier to add more cases later

... of course this is an art, not a science, and in some cases you can't follow the hard-and-fast rule, I frequently find myself writing code like:

if (p == NULL) {
   doSomething();
} else {
   doSomethingElse();
}

...justified by the fact that is very obvious and implicit from the first if condition what the else is used for.

David Claridge
+1  A: 

else was invented and is used for good reason. Where you use it should be dictated by the logic that you trying to achieve, not a contrived sense of style.

Some argue that it is more self-documenting by using explicit conditions in an else if; however, this may lead to gaps in logic with default or catch all conditions.

Also, some say that it is easier to modify in the future. This argument is bunk. Using design patterns and writing modular code is something that is easier to modify in the future, writing one line shouldn't qualify for these kinds of statements.

Justin Johnson