简化java if语句

发布于 2024-11-27 17:12:20 字数 246 浏览 2 评论 0原文

我可以简化这个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

青柠芒果 2024-12-04 17:12:20

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

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

应该工作:

if (A == null && (A = staticGetMethod()) == null) {
    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() { ... };
}
满意归宿 2024-12-04 17:12:20

将构建逻辑放入工厂方法中,

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

}

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

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

谜兔 2024-12-04 17:12:20

您可以使用三元运算符而不是 if 语句:

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

也就是说,说实话,我会坚持使用您所拥有的内容 - 只不过我会为第二个条件添加一个块,而不是而不是将声明与其内嵌。

You can use a ternary operator instead of the if statements:

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.

自此以后,行同陌路 2024-12-04 17:12:20

这是 Charles Goodwin 的代码,稍作修改:

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

我使用 AND 而不是 OR

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

故事还在继续 2024-12-04 17:12:20

我认为这是最好的方法:

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

I think this is the best way to do it:

if(A == null)
{
    if((A = staticGetMethod()) == null) A = new BackupAContent() { ... };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文