Gracefully avoiding NullPointerException in Java

前端 未结 9 1341
夕颜
夕颜 2020-11-30 04:02

Consider this line:

if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....

Obviously this line is a potential bug, the attribute

相关标签:
9条回答
  • 2020-11-30 04:34

    Here is my approach, needs a PropertyUtil class though, but its only written once:

    /**
     * Generic method to encapsulate type casting and preventing nullPointers.
     * 
     * @param <T>          The Type expected from the result value.
     * @param o            The object to cast.
     * @param typedDefault The default value, should be of Type T.
     * 
     * @return Type casted o, of default.
     */
    public static <T> T getOrDefault (Object o, T typedDefault) {
        if (null == o) {
            return typedDefault;
        }
        return (T) o;
    }
    

    Client code can do this:

    PropertyUtil.getOrDefault(obj.getAttribute("someAttr"), "").equals("true");
    

    or, for a list:

    PropertyUtil.getOrDefault(
        genericObjectMap.get(MY_LIST_KEY), Collections.EMPTY_LIST
    ).contains(element);
    

    Or to a consumer of List, that would reject Object:

    consumeOnlyList(
        PropertyUtil.getOrDefault(
            enericObjectMap.get(MY_LIST_KEY), Collections.EMPTY_LIST
        )
    )
    

    The default might be an impl of the null object pattern https://en.wikipedia.org/wiki/Null_Object_pattern

    0 讨论(0)
  • 2020-11-30 04:35

    Util.isEmpty(string) - returns string == null || string.trim().isEmpty() Util.notNull(string) returns "" if string == null, string otherwise. Util.isNotEmpty(string) returns ! Util.isEmpty(string)

    And we have a convention that for strings, Util.isEmpty(string) semantically means true and Util.isNotEmpty(string) semantically means false.

    0 讨论(0)
  • 2020-11-30 04:36

    In the second option, you can take advantage of short-circuiting &&:

    String attr = object.getAttribute("someAttr");
    if (attr != null && attr.equals("true")) { // ....
    
    0 讨论(0)
  • 2020-11-30 04:38

    It's a very good question. I usually use the not graceful:

    if (object.getAttribute("someAttr") != null && object.getAttribute("someAttr").equals("true")) { // ....
    

    (and I will not use it anymore)

    0 讨论(0)
  • 2020-11-30 04:45

    I like option 1 and I would argue that it is readable enough.

    Option 3 btw would be to introduce a getAttribute method that takes a default value as a parameter.

    0 讨论(0)
  • 2020-11-30 04:45

    Always aspire for shorter code, given that both are functionaly equivalent. Especially in case like this where readability is not sacrificed.

    0 讨论(0)
提交回复
热议问题