mercredi 17 février 2021

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.

Aucun commentaire:

Enregistrer un commentaire