0

次のコードは、変数nullを初期化するために 1 行で 2 回チェックする最良の方法ですか?final

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

4 に答える 4

8

まあ、&&代わりに条件付きの単一の条件を使用するでしょう:

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

複数の場所でこれを行う必要がある場合は、メソッドでラップすることをお勧めします。

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

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

次に、変数宣言を簡素化できます。

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

text.getText()複数回の呼び出しが問題になるかどうかは、シナリオによって異なることに注意してください。場合によっては、それが悪い考えであり、それを避けるためにコードを再構築する必要があります。確かなことは言えませんが、検討する価値はあります。

于 2013-06-17T05:59:44.227 に答える
3

あなたはこれを行うことができます :

final String textValue = (text != null && text.getText() != null) ? text.getText() : "" ;
于 2013-06-17T06:00:00.463 に答える
0

「最高」の意味がわかりません(最もプログラマーフレンドリーですか?最も効率的な実行ですか?)

しかし、プログラマーに優しい代替手段は次のとおりです。

final String textValue = (text != null && text.getText() != null) ? text.getText() : "";
于 2013-06-17T06:01:51.940 に答える
0

この行はメソッドのどこかにあると思います。したがって、これはより読みやすくなります。

String value = "";
if (text != null && text.getText() != null) {
  value = text.getText();
}
final String textValue = value;
于 2013-06-17T06:02:30.967 に答える