单行双重检查

Moh*_*hin 0 java null final

以下代码是null在一行中检查两次初始化final变量的最佳方法吗?

final String textValue = text != null ? text.getText() != null ? text.getText() : "" : "";
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

好吧,我可能会使用一个带&&条件的条件:

final String textValue = text != null && text.getText() != null ? text.getText()
                                                                : "";
Run Code Online (Sandbox Code Playgroud)

如果您发现需要在多个地方执行此操作,您可能希望将其包装在一个方法中:

// We don't know what the type of text is here... adjust appropriately.
public static String getTextOrDefault(TextBox text, String defaultValue)
{
    return text != null && text.getText() != null ? text.getText()
                                                  : defaultValue;
}
Run Code Online (Sandbox Code Playgroud)

或调整以避免getText()多次调用:

// We don't know what the type of text is here... adjust appropriately.
public static String getTextOrDefault(TextBox text, String defaultValue)
{
    if (text == null)
    {
        return defaultValue;
    }
    String textValue = text.getText();
    return textValue != null ? text.getText() : defaultValue;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以简化变量声明:

final String textValue = SomeHelper.getTextOrDefault(text, "");
Run Code Online (Sandbox Code Playgroud)

请注意,调用text.getText()多次是一个问题取决于您的方案 - 在某些情况下,这将是一个坏主意,您应该重新构建您的代码以避免它.我们无法确定,但值得考虑.