更好的方法来处理android中的空值?

时间:2016-04-27 06:26:52

标签: android software-quality

每当我需要从android中的其他活动/意图等获取一些数据时,我的代码基本上必须遵循以下逻辑:

Intent intent = getIntent();

if (intent != null) {
    String intentAction = intent.getAction();

    if (intentAction != null && intentAction.equals("whatever")) {

    // Do some stuff now that we know there are now  null values
    }
}

在我看来,非常详细且非常嵌套的代码,每次我这样做,我都认为自己必须有一个更好的方式"。

  

那有什么,那会是什么?

3 个答案:

答案 0 :(得分:0)

您可以将这些if-statements合并为一个。您不会收到错误,因为代码将在&&返回false之前的第一个参数后“退出”。

Intent intent = getIntent();

if (intent != null && intent.getAction() != null && intent.getAction().equals("whatever") {

    // Do some stuff now that we know there are now  null values

}

或者这是一个更短的方式,感谢@Tomkarho的建议。

Intent intent = getIntent();

if (intent != null && "whatever".equals(intent.getAction()) {

    // Do some stuff now that we know there are now  null values

}

答案 1 :(得分:0)

我个人只是创建一些辅助方法来清理主逻辑。如果这是经常出现的代码,您可以创建一个基类getIntentAction类来保存Activity方法,或者在帮助器中创建一个静态方法,该方法可以使用Intent或其{ {1}}作为参数。

对于字符串比较,您可以使用TextUtils.equals()。或者,如果您有一个包含操作名称的String,则可以将其用作equals方法的左侧。请确保您以后不要交换订单。

一些示例代码:

public static final String WhateverAction = "whatever";

public String getIntentAction()
{
    Intent intent = getIntent();
    return intent == null ? null : intent.getAction();
}

在左侧使用比较字符串:

public void processMyIntent()
{
    String action = getIntentAction();
    if(WhateverAction.equals(action))
    {
        // do something
    }
    else if("thisAlsoWorksAction".equals(action)
    {
        // do something else
    }
    else
    {
        // got null or unexpected value
    }
}

使用TextUtils

public void processMyIntentTextUtils()
{
    String action = getIntentAction();
    if(TextUtils.equals(action, WhateverAction))
    {
        // do something
    }
    if(TextUtils.equals(action, "anotherAction"))
    {
        // do something else
    }
    else
    {
        // got null or unexpected value
    }
}

使用开关:

public void processMyIntentSwitch()
{
    String action = getIntentAction();
    switch(action)
    {
        case WhateverAction:
           //...
           break;

        default:
           // got null or unexpected value
    }
}

你也可以通过这种单线程来避免使用getIntentAction方法,尽管它有点罗嗦:

String intentAction = getIntent() != null ? getIntent().getAction() : null;

答案 2 :(得分:-2)

一个糟糕的实践,但更短(并且没有):

try {
  switch (getIntent().getAction()) {
       case "whatever": ...
            ...
         }
} catch e {}
相关问题