[英]Simplify java if statement
如果构造,我可以简化这个java吗? 对我来说似乎太冗长了,我想让它更短。
A是持久性Object,如果第一次访问它的上下文,它将为null。 比A是instatniated和给定内容,如果失败,一些备份内容给A。
if (A == null) {
A = staticGetMethod();
if (A == null) A = new BackupAContent() { ... };
}
更新:或者您可以简单地删除嵌套,因为它仍然会以相同的方式运行。
if (A == null) {
A = staticGetMethod();
}
if (A == null) {
new BackupAContent() { ... };
}
应该管用:
if (A == null && (A = staticGetMethod()) == null) {
new BackupAContent() { ... };
}
将您的构建逻辑放在工厂方法中
if (objA == null) {
objA = getAInstance();
}
将Charles建议的代码封装到实现Factory_method_pattern的方法中
您可以使用三元运算符而不是if
语句:
a = a ? a : staticGetMethod();
a = a ? a : new BackupAContent();
也就是说,我坚持你所拥有的,说实话 - 除了我会为第二个条件添加一个块而不是将该语句与其内联。
这是查尔斯古德温的代码略有变化:
if (A == null && (A = staticGetMethod()) == null) {
new BackupAContent() { ... };
}
我使用AND而不是OR
我认为这是最好的方法:
if(A == null)
{
if((A = staticGetMethod()) == null) A = new BackupAContent() { ... };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.