Search code examples
javanullfinal

Double null check in single line


Is the following code the best way to check for null for two times in a single line for initializaing a final variable?

final String textValue = text != null ? text.getText() != null ? text.getText() : "" : "";

Solution

  • Well I'd probably use a single conditional with an && condition instead:

    final String textValue = text != null && text.getText() != null ? text.getText()
                                                                    : "";
    

    If you find you need to do this in more than one place, you may well want to wrap it in a method:

    // 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;
    }
    

    Or adjusted to avoid calling getText() more than once:

    // 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;
    }
    

    Then you can simplify your variable declaration:

    final String textValue = SomeHelper.getTextOrDefault(text, "");
    

    Note that whether calling text.getText() more than once is a problem depends on your scenario - in some cases it would be a bad idea, and you should restructure your code to avoid it. We can't tell for sure, but it's worth considering.