Search code examples
javaif-statementstylesstandards

Should You Use an Else Statement if All Other Branches Return?


I am currently working with Java, though this question is relevant for other languages as well. If ALL "if" and "else if" branches return or throw an exception, should you still use an else statement? Here's an oversimplified example of accessing the index of a linked list with a head pointer:

public Node getIndex(int index){  
    //Make sure it's a non-negative index  
    if(index < 0) {  
        throw new IndexOutOfBoundsException();  
    }  
    //Index 0 is the head, no need to iterate  
    else if(index == 0) {  
        return head;  
    }  
    //Option A
    else {  
        //Use a for loop to iterate to the element inside the else statement  
    }  
    //Option B
    //Use a for loop to iterate to the element outside of the if/else block  
}  

This portion of code would function exactly the same with option A or option B since index <= 0 would always throw or return before reaching it. Functionally, I don't believe it's necessary to have the else statement here. Are there any agreed upon standards for this or is it a personal preference? My intuition says to remove the "else" statement in these situations.


Solution

  • I think having the else is confusing, because it is sending mixed signals: when I see the else I think there must be some path in the if statement that doesn’t return that I need to look out for. Also I think it is easier to read code that isn’t deeply nested.

    Here is a quote from a site that tries to list standards and good practices, http://www.javapractices.com/topic/TopicAction.do?Id=114:

    Some programmers find that, occasionally, some methods become clearer if multiple return statements are used, instead of the usual single point of exit. This technique can be easily abused, and should be used with care. It's mainly used to replace nested if structures. Multiple return statements seem to work well for "guard code" at the beginning of a method, in which the main body of the method is executed only if certain conditions are satisfied.

    Here is some of the example code on that page:

    public final class Automobile {
    
      @Override public boolean equals(Object aThat) {
        if (this == aThat) return true;
        if (!(aThat instanceof Automobile)) return false;
        Automobile that = (Automobile)aThat;
        for(int i = 0; i < this.getSigFields().length; ++i){
          if (!Objects.equals(this.getSigFields()[i], that.getSigFields()[i])){
            return false;
          }
        }
        return true;
      }
    

    There isn’t any particular claim to authority here though. And you will find people who really don’t like methods that have more than one return statement.