I've got this method at the moment that I am trying to refactor.
public static boolean isEmpty(Object value) {
boolean empty = false;
if (value instanceof String && ((String) value).isEmpty()) {
empty = true;
} else if (value instanceof List && ((List<?>) value).isEmpty()) {
empty = true;
} else if (value instanceof String[] && ArrayUtils.isEmpty((String[]) value)) {
empty = true;
} else if (value == null) {
empty = true;
}
return empty;
}
Is there an obviously better way to do this that I am missing?
I know I could put all the conditions on one if
statement using chained ||
statements, but I don't really see how that is better than what I've got now.
As mentioned in deHaar's answer, the code can be improved by using if-return
combinations.
You should however generalize your code a bit more, e.g. support all array types, not just string arrays, and support all collection types, not just lists.
Similarly, String
implements an interface named CharSequence
, so support that instead. That way the code will support classes like StringBuilder
and StringBuffer
too.
public static boolean isEmpty(Object value) {
if (value == null)
return true;
if (value instanceof CharSequence) // String, StringBuilder, StringBuffer, ...
return ((CharSequence) value).isEmpty();
if (value instanceof Collection) // List, Set, Queue, Deque, ...
return ((Collection<?>) value).isEmpty();
if (value instanceof Map)
return ((Map<?,?>) value).isEmpty();
if (value.getClass().isArray()) // All array types
return (Array.getLength(value) == 0);
return false;
}
Code was modified to to use pure built-in methods, i.e. to not rely on ArrayUtils
.
UPDATED: Added support for primitive arrays.
The above implementation is a close match to the JSP EL empty
operator:
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false