aherbert commented on code in PR #1063: URL: https://github.com/apache/commons-lang/pull/1063#discussion_r1224218659
########## src/main/java/org/apache/commons/lang3/ObjectUtils.java: ########## @@ -595,7 +595,11 @@ public static short CONST_SHORT(final int v) { * TODO Rename to getIfNull in 4.0 */ public static <T> T defaultIfNull(final T object, final T defaultValue) { - return object != null ? object : defaultValue; + try { Review Comment: This will not catch the exception in your example: ```Java defaultIfNull(list.get(0).getValue(), "helloDefault"); ``` Equivalent to: ```Java Object o = list.get(0).getValue(); // NPE generated here ObjectUtils.defaultIfNull(o, "helloDefault"); ``` What you require is a method that uses a `Supplier` to create the object. Your supplier would be responsible for catching the NPE if you use `ObjectUtils.getFirstNonNull`: ```Java List<Object> list = Collections.emptyList(); Object object = ObjectUtils.getFirstNonNull( () -> { try { return list.get(0).getValue(); } catch (NullPointerException ignored) { return null; }}, () -> "helloDefault" ); ``` In this scenario it makes more sense to check for null using a classic `if` or `ternary` statement to avoid the NPE and let the `ObjectUtils` handle the null from `getValue`: ```Java Object o = ObjectUtils.defaultIfNull(list.isEmpty() ? null : list.get(0).getValue(), "helloDefault"); ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@commons.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org