1

我有一个带有 5 个内部字符串变量的对象,但其中 3 个是可选的。我可以为每个可能的组合创建一个构造函数,或者我可以调用通用构造函数并将一些空字符串传递给它。后一种情况对我来说很有趣,如果我在调用构造函数时可以执行以下操作:

String a = "Mandatory";
...
String e = "" + getVariableE(); //getVariableX() could return null, 
                                //then it would be "".
                                //This is a "long" fetch statement.

new objectA(a, b, c, d, e); 

另一种选择:

String d = "";
String e = "";
if(getVariableD!=null)  //Remember pretty long fetch statement (ugly looking)
     d = getVariableD();
if(getVariableE!=null)
    e = getVariableE();

new objectA(a, b, c, d, e);

我看不到在不使用多个 if 语句的情况下使用多个构造函数。

new objectA(a, b, c);
new objectA(a, b, c, d)

我认为构造函数在这里可能不是一个因素,而只是将线条设置为“”或其他东西的方式;尽管如此,我还是留下了它,以防我错过了什么。

这是简单的 objectA 类

public class objectA {
String a; //Needed
String b; //Needed
String c; //Optional
String d; //Optional
String e; //Optional
/*
 * Possible constructor
*/
    void object(String a, String b, String c, String d, String e) {
    this.a = a;
    ...
    this.e = e;
    }

注意:getVariableX() 从 XML 文件中获取一个属性,所以我可以强制它必须包含一个字符串,但我不认为这会很好。更好地赋予 XML 文件灵活性。

4

3 回答 3

1
if(getVariableD!=null) {
    d = getVariableD();
}

可以转换为三元运算符:

d = getVariableD != null ? getVariableD() : "";

注意:您应该始终更喜欢代码可读性而不是简洁性。

Elvis 运算符是为 Java 7 提出的语法糖,但从未成功。

于 2013-02-14T08:34:29.260 回答
1

如果getVariableD()返回一个字符串,您还可以使用GuavaStrings.nullToEmpty()中的方法来避免键入(和评估)getVariableD() 两次。

当然,您可以为任意对象编写类似的实用方法:

/** Returns {@code obj.toString()}, or {@code ""} if {@code obj} is {@code null}. */
static String safeToString(@Nullable Object obj) {
  return obj == null ? "" : obj.toString();
}

然后做:

String d = safeToString(getVariableD());
于 2013-02-14T10:39:31.883 回答
1

您可以使用 Java 8 中包含的 Optional 类。

this.d = Optional.ofNullable(d).orElse("");
于 2021-08-06T06:49:08.967 回答