Search code examples
javaeclipsetemplateseclipse-jdt

eclipse autogenerates !=null recursive calls


given a java code such as:

Something v = a.getB().getC().getD().getE();

Is there a way in Eclipse (templates or external plugins) to generate a safe chain call as:

if(a!=null && 
   a.getB()!=null &&
   a.getB().getC()!=null &&
   a.getB().getC().getD()!=null &&        
   a.getB().getC().getD().getE()!=null){
          Something v = a.getB().getC().getD().getE(); 
   }        

Solution

  • Have you given any thought to a try{} catch(NullPointerException e){} block? It might feel less elegant, but it will stop your code if any of the method calls fails because the previous one returned null, and it will give you the chance to give the default value if it is null.

    Another option would be something like this:

    Something v = /*Default Value*/ // Will be overwritten if subsequent methods succeed.
    Object temp = a.getB(); // Use whatever Object type getB() returns.
    if(temp != null){
        temp = temp.getC(); 
        /* If getC() returns a different type of object, 
         * either use a different variable or make the temp variable even broader 
         * (such as the generic Object type) */
        if(temp != null){
            temp = temp.getD();
            if(temp != null){
                temp = temp.getE();
                if(temp != null)
                    v = temp; 
                    /* If all previous calls returned something substantial, 
                     * v will be something useful */
                }//if(getE() != null)
            }//if(getD() != null)
        }//if(getC() != null)
    }//if(getB() != null)
    

    If you want, you could use a slightly less CPU efficient, but easier to read, version by not nesting the if statements. If all of the if statements are executed after eachother, a single null will prevent all of the next statements from executing, although its value will still be checked every time.

    As far as generating these statements, I'm not really sure. That will really depend on how far in advance you can predict what new methods will be available from the Object returned by previous method calls. If you're aiming for auto-generation of code, you might be better off with my first suggestion: try-catch