次のコードは、変数null
を初期化するために 1 行で 2 回チェックする最良の方法ですか?final
final String textValue = text != null ? text.getText() != null ? text.getText() : "" : "";
まあ、&&
代わりに条件付きの単一の条件を使用するでしょう:
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()
複数回の呼び出しが問題になるかどうかは、シナリオによって異なることに注意してください。場合によっては、それが悪い考えであり、それを避けるためにコードを再構築する必要があります。確かなことは言えませんが、検討する価値はあります。
あなたはこれを行うことができます :
final String textValue = (text != null && text.getText() != null) ? text.getText() : "" ;
「最高」の意味がわかりません(最もプログラマーフレンドリーですか?最も効率的な実行ですか?)
しかし、プログラマーに優しい代替手段は次のとおりです。
final String textValue = (text != null && text.getText() != null) ? text.getText() : "";
この行はメソッドのどこかにあると思います。したがって、これはより読みやすくなります。
String value = "";
if (text != null && text.getText() != null) {
value = text.getText();
}
final String textValue = value;