Get rid of the useless return statement

I am trying to reorganize some code and make it easier to read. I noticed that I have some unnecessary return statements at the end of some functions. Here is 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 a function is misleading, since it assumes that it can be reached at some point. How can I prevent this?

Please note that I'm doing error handling in some other place, so I can be sure that someFunctionit will always return somethingElse.

+4
source share
1 answer

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

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

    panic("unreachable")
} 

.

+10

Source: https://habr.com/ru/post/1695525/


All Articles