Check if last getter in method chain is not null

前端 未结 3 714
春和景丽
春和景丽 2020-12-06 12:31

In code we have got a lot of chain methods, for example obj.getA().getB().getC().getD(). I want to create helper class which will check if method getD()

3条回答
  •  太阳男子
    2020-12-06 12:52

    As already stated, the true solution is refactoring.

    In the meantime, you could just wrap your first workaround in a function:

    static D getD(MyClass obj) {
    
        try {
            return obj.getA().getB().getC().getD();
        }
        catch (NullPointerException e) {
            return null; // Or even better, some default D
        }
    }
    

    At the caller site:

    D d = getD(obj);
    

    At least you don't have to trash the caller with try-catch blocks. You still need to handle the errors somehow, when some of the intermediate getX() call returns a null and so d becomes null. The best would be to return some default D in the wrapper function.


    I don't see how the two options you list at the end of your question would help if any of the intermediate getX() returns a null; you will get a NullPointerException.

提交回复
热议问题