对于if-else条件,哪种更好的做法? [英] Which is a better practice for if-else condition?

查看:125
本文介绍了对于if-else条件,哪种更好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个选项中哪一个更好?

Which one of these two options are better?

if(obj.getType!=null && obj.getData()!=null)
{
  // Do something
}
elseif(obj.getData==null)
{
  // Do other thing
}

*OR*

if(obj.getType!=null)
{  
  if(obj.getData!=null)
  {
    // Do something
  }
  else
 {
   // Do other thing
 }
}

主要的疑点是为什么要以第一种方式对getData进行两次空检查?第二个选项只执行一次。

The major point of doubt is why to do null check for getData twice in the first way? The second option does it only once.

推荐答案

这取决于你需要什么。

It depends on what you need.

考虑您有一项要求规定您收集代表大于0的值的2个数据点,并且您必须就是否以及哪些值无效提供反馈。

Consider you have a requirement that stipulates you collect 2 data points that represent values that are greater than 0, and you have to give feedback on if and which values are invalid.

public Data(int x, int y) 
{
    if (x <= 0 || y <= 0) { 
         throw new IllegalArgumentException("Invalid data provided, got (x: %d, y:%d)", x, y); 
    }
}

注意检查null然后检查条件是一个相当正常的模式,称为空值守卫。

Note that checking for null and then checking for a condition is a fairly normal pattern called a null guard.

public void setValue(SomeValue o) { 
    if (o == null || o.Value <= 0) { 
        // code to handle bad value
    }
}

另一方面,如果您有一组需要按顺序检查的条件,如果不满足则会失败,您可以(不推荐)使用链式如果就像你有:

On the other hand, if you have a set of conditions that need to be checked in order, and fail out if one isn't met, you can (not recommended) use chained ifs like you have:

public void someOperation() 
{ 
    if (condition) 
    { 
        if (condition2) 
        {
            if (condition3) 
            { 
                // operation here
            } 
        }
    }
}

请注意,虽然您没有明确提及控制语句以外的其他内容,但如果您的情况类似于前面的示例,我会强烈建议重构通过反转条件进行条件检查,如果检查很复杂,则将它们重构为返回 boolean 的方法。

Note that although you don't explicitly mention something other than control statements, if you have a situation similar to the preceeding example, I would strongly recommend refactoring the condition checks by inverting them, and if the checks are complicated, refactor them out to methods returning boolean.

public void someOperation() 
{ 
    if (!condition) 
    {
        // code to fail out
    }

    if (!condition2) 
    {
        // code to fail out
    }

    if (!complexCondition())
    {
        // code to fail out
    }

    // operation here
}

这篇关于对于if-else条件,哪种更好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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