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 fai开发者_开发问答ls, 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() { ... };
}
精彩评论