简化java if语句
我可以简化这个java if 构造吗?对我来说似乎太冗长了,我想缩短它。
A 是持久对象,如果第一次访问它的上下文,则该对象将为 null。然后 A 被实例化并给出内容,如果失败,则会向 A 提供一些备份内容。
if (A == null) {
A = staticGetMethod();
if (A == null) A = new BackupAContent() { ... };
}
Can I simplify this java if construct? 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. Than A is instatniated and given content, and if this fails, some backup content is given to A.
if (A == null) {
A = staticGetMethod();
if (A == null) A = new BackupAContent() { ... };
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更新:或者您可以简单地删除嵌套,因为它的行为方式仍然相同。
应该工作:
Update: Or you could simply remove the nesting as it will still behave the same way.
Should work:
将构建逻辑放入工厂方法中,
将 Charles 建议的代码封装到实现 Factory_method_pattern 的方法中
Put your building logic in factory method
encapsulate the code suggested by Charles into a method to implement Factory_method_pattern
您可以使用三元运算符而不是
if
语句:也就是说,说实话,我会坚持使用您所拥有的内容 - 只不过我会为第二个条件添加一个块,而不是而不是将声明与其内嵌。
You can use a ternary operator instead of the
if
statements: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.
这是 Charles Goodwin 的代码,稍作修改:
我使用 AND 而不是 OR
This is Charles Goodwin's code with a slight change:
I used an AND instead of an OR
我认为这是最好的方法:
I think this is the best way to do it: