简体   繁体   English

简化java if语句

[英]Simplify java if statement

Can I simplify this java if construct? 如果构造,我可以简化这个java吗? It seems too verbose to me, I'd like to have it shorter. 对我来说似乎太冗长了,我想让它更短。

A is persistent Object, which will be null if it's context is accessed first time. A是持久性Object,如果第一次访问它的上下文,它将为null。 Than A is instatniated and given content, and if this fails, some backup content is given to A. 比A是instatniated和给定内容,如果失败,一些备份内容给A。

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

Update: Or you could simply remove the nesting as it will still behave the same way. 更新:或者您可以简单地删除嵌套,因为它仍然会以相同的方式运行。

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

Should work: 应该管用:

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

Put your building logic in factory method 将您的构建逻辑放在工厂方法中

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

}

encapsulate the code suggested by Charles into a method to implement Factory_method_pattern 将Charles建议的代码封装到实现Factory_method_pattern的方法中

You can use a ternary operator instead of the if statements: 您可以使用三元运算符而不是if语句:

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

That said, I'd stick with what you've got, to be honest -- except that I would add a block for the second conditional rather than putting the statement inline with it. 也就是说,我坚持你所拥有的,说实话 - 除了我会为第二个条件添加一个块而不是将该语句与其内联。

This is Charles Goodwin's code with a slight change: 这是查尔斯古德温的代码略有变化:

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

I used an AND instead of an OR 我使用AND而不是OR

I think this is the best way to do it: 我认为这是最好的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM