Search code examples
javaif-statementverbosity

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

Solution

  • 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