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.

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

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端