dounong5373 2018-03-29 11:18
浏览 124
已采纳

摆脱无用的return语句

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.

  • 写回答

1条回答 默认 最新

  • dora0817 2018-03-29 11:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?