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 <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
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.
In the second option, you can take advantage of short-circuiting &&
:
String attr = object.getAttribute("someAttr");
if (attr != null && attr.equals("true")) { // ....
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)
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.
Always aspire for shorter code, given that both are functionaly equivalent. Especially in case like this where readability is not sacrificed.