Consider this line:
if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....
Obviously this line is a potential bug, the attribute
Here is my approach, needs a PropertyUtil
class though, but its only written once:
/**
* Generic method to encapsulate type casting and preventing nullPointers.
*
* @param 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 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