Search code examples
loopsgoreturnreturn-value

Get rid of useless return statement


I am trying to refactor some code and make it easier to read. I noticed that I have some unnecessary return statements at the end of some functions. Here a conceptual example:

func someFunction(a []arr) int {
    for _,v := range a {
        if v == something {
            // will defenitly get here at some point! 
            return somethingElse
        }
    }
    return -1 // never ever happens! 
} 

In my opinion the return statement at the end of the function is misleading, because it suggests, that it may be reached at some point. How do I prevent it?

Please note, that I do error handling at some other point, which is why I can be sure, that someFunction will always return somethingElse.


Solution

  • Panic instead of returning fake value at the end of a function:

    func someFunction(a []arr) int {
        for _,v := range a {
            if v == something {
                // will defenitly get here at some point! 
                return somethingElse
            }
        }
    
        panic("unreachable")
    } 
    

    This is a common pattern in standard library.