Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
JDoe6213981 Avatar asked Mar 29 '18 11:03

JDoe6213981


1 Answers

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.

like image 173
Jakub Moravec Avatar answered Oct 15 '22 14:10

Jakub Moravec