java - 如何避免 Java 中的多个 If 语句?

标签 java if-statement null refactoring nullable

如何重构这个方法?

public String getFirstOrLastNameOrBoth() {
    if (this.getFirstname() != null && this.getLastname() != null) {
        return this.getFirstname() + this.getLastname();
    } else if (this.getFirstname() != null && this.getLastname() == null){
        return this.getFirstname();
    } else if (this.getLastname() != null && this.getFirstname() == null){
        return this.getLastname();
    }
    return 0.0;
}

最佳答案

    public String getFirstOrLastNameOrBoth() {
        return (getFirstname() == null ? "" : getFirstname()) 
             + (getLastname() == null ? "" : getLastname());
    }

关于java - 如何避免 Java 中的多个 If 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71870274/

相关文章:

sql - Firebird VARCHAR 中的 NULL 字符

ssl - Java 7 和无法生成 DH key 对

java - 世界上有更多的 body 时 FPS 速度较慢

java 。输出错误

python - Lambda 而不是 "if"语句

if-statement - Lua if A != (X or Y or Z)?

c - 当没有更多空间时,编译器如何添加空终止符?

sql - SQL查询结果中用空白单元格替换 "(null)"

java - 我们可以在App Update中完全更改android源代码吗?

java - 如何在javafx中使按钮只按一次