简体   繁体   中英

Simplify java if statement

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() { ... };
}

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

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.

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

I think this is the best way to do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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