有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

简化java if语句

我可以简化这个java if构造吗?我觉得太冗长了,我想把它缩短一点

是持久对象,如果第一次访问它的上下文,它将为null。然后A将安装并提供内容,如果安装失败,则会向A提供一些备份内容

if (A == null) {
    A = staticGetMethod();
    if (A == null) A = new BackupAContent() { ... };
}

共 (5) 个答案

  1. # 1 楼答案

    这是查尔斯·古德温的代码,稍作改动:

    if (A == null && (A = staticGetMethod()) == null) {
    new BackupAContent() { ... };
    }
    

    我用AND代替OR

  2. # 2 楼答案

    将你的建筑逻辑放在工厂方法中

    if (objA == null) {
        objA = getAInstance();
    
    }
    

    将Charles建议的代码封装到实现Factory_method_pattern的方法中

  3. # 3 楼答案

    更新:或者您可以简单地删除嵌套,因为它仍将以相同的方式运行

    if (A == null) {
        A = staticGetMethod();
    }
    if (A == null) {
        new BackupAContent() { ... };
    }
    

    应该有效:

    if (A == null && (A = staticGetMethod()) == null) {
        new BackupAContent() { ... };
    }
    
  4. # 4 楼答案

    可以使用三元运算符代替if语句:

    a = a ? a : staticGetMethod();
    a = a ? a : new BackupAContent();
    

    也就是说,老实说,我会坚持你所得到的——除了我会为第二个条件添加一个块,而不是将语句与之内联

  5. # 5 楼答案

    我认为这是最好的方法:

    if(A == null)
    {
        if((A = staticGetMethod()) == null) A = new BackupAContent() { ... };
    }