0

Please find my below code that am checking for null using ternary operator before am setting the value to my bean class attributes.

doc.setCatalog_description(sourceAsMap != null && sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);

Is there anyother way to simplify this code like below., Am just exploring by using org.apache.commons.lang3.ObjectUtils; methods. But am not sure that it is correct or not.

doc.setCatalog_description(ObjectUtils.identityToString(sourceAsMap.get("catalog_description")));
Karthikeyan
  • 1,927
  • 6
  • 44
  • 109
  • In your proposed solution if sourceMap is null then a NullPointerException will occur. – Archit Jul 10 '18 at 11:25
  • 1
    If you want to handle missing keys in sourceMap and return a default value then java 8 provides this . use `sourceMap.getOrDefault(key, defaultVal)` – Archit Jul 10 '18 at 11:27
  • Are you looking for a short way to extract catalog_description if all conditions are met? `ObjectUtils.identityToString`will return a very technical description based on the class name and the hash code of the given object. The first and the latter are different things. – LuCio Jul 10 '18 at 11:28

3 Answers3

1

I think you are looking for the method ObjectUtils.toString(Object).

if (sourceAsMap != null) {
    final String description = ObjectUtils.toString(sourceAsMap.get("catalog_description"));
    doc.setCatalog_description(description);
}

If you are using jdk7 or higher, you can replace the method by java.util.Objects.toString(Object).

if (sourceAsMap != null) {
    final String description = Objects.toString(sourceAsMap.get("catalog_description"));
    doc.setCatalog_description(description);
}

I don't know if sourceAsMap can be null, but if you are setting several parameters, you should check if it is null just once.

0

In the interest of readability and clarity I would suggest just extracting this bit of functionality into its own method:

String getDescOrNull(Map<String, Object> sourceAsMap) {
    final String key = "catalog_description";
    if (sourceAsMap == null || !sourceAsMap.containsKey(key)) {
        return null;
    }
    return sourceAsMap.get(key);
}

then:

doc.setCatalog_description(getDescOrNull(sourceAsMap));
stephan f
  • 589
  • 5
  • 16
0

am checking for null using ternary operator before am setting the value to my bean class attributes

So I think you need to set multiple bean attributes from the map.

Best and simple solution will be to check null condition on sourceMap for once and then use ternary operator for setting attributes.

 if(sourceAsMap != null){
      doc.setCatalog_description(sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
      doc.setAnother_description(sourceAsMap.get("another_description") != null ? sourceAsMap.get("another_description").toString() : null);
    }
Ronald James
  • 647
  • 1
  • 5
  • 13