编程首选项 - 使用具有多个return语句的else ifs? [英] Programming preference - use else ifs with multiple return statements?

查看:191
本文介绍了编程首选项 - 使用具有多个return语句的else ifs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

public String getTemperatureMessage(double temp)
{
    if(temp < 32)
        return "Freezing";
    else if(temp < 60)
        return "Brr";
    else if(temp < 80)
        return "Comfortable";
    else
        return "Too hot";
}

关于上面的代码片段,其他ifs在技术上是多余的,不需要完全改变行为。但是,我倾向于将它们放在那里以强调条件是排他性的。你的想法是什么?不必要或更清楚?

Regarding the code snippet above, the else ifs are technically superfluous and don't change the behavior at all. However, I tend to like to put them in there to emphasize that the conditions are exclusive. What are your thoughts? Unnecessary or more clear?

推荐答案

有人会说多重回报就是问题所在。但这不是我的观点。

Some would say that multiples return would be the problem here. But it's not really my point.

对于我的观点,if / else if非常重要,因为即使在你的情况下你返回一些值,删除elses意味着你无论如何也不会把它们放在一边,如果不在这里,那就意味着完全不同的事情。

For my point of view, the if/else if is really important, because even if in your case you return some value, removing the elses would mean that you wouldn't put them anyway, and that would mean a totally different thing if the returns were not here.

另外,想象有一天有人想编辑你的代码,并清理一次返回,这个人可能会误解你的代码,并犯这样一个严重的错误:

Plus, imagine someday someone want to edit your code, and clean it up for a single return, this person could misunderstand your code and do a grave mistake like this :

public String getTemperatureMessage(double temp){
    String message;
    if(temp < 32)
        message = "Freezing";
    if(temp < 60)
        message = "Brr";
    if(temp < 80)
        message = "Comfortable";
    else 
        message = "Too hot";
    return message;
}

为了澄清我的观点,保持精益,它保持你的代码清晰。

To clarify my point of view, keep the elses, it keep your code clear.

这篇关于编程首选项 - 使用具有多个return语句的else ifs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆