Reputation: 41
I have this code and I want to check if the code is not existing in the map.. Is it better to return primitive type and check if its not equal to zero? or its better to return a Long wrapper and return null then check if its null.. Is there any advantage with each other?
code = getCurrencyCode(parameterMap);
if (code != 0) {
//do something with the code
}
private static long getCurrencyCode(Map<String, String> parameterMap) {
for (Map.Entry<String, String> entry : MapUtils.emptyIfNull(parameterMap).entrySet()) {
if (StringUtils.startsWith(entry.getKey(), CONFIG_CURRENCY)) {
return NumberUtils.createLong(entry.getValue());
}
}
return 0;
}
OR
code = getCurrencyCode(parameterMap);
if (code != null) {
//do something with the code
}
private static Long getCurrencyCode(Map<String, String> parameterMap) {
for (Map.Entry<String, String> entry : MapUtils.emptyIfNull(parameterMap).entrySet()) {
if (StringUtils.startsWith(entry.getKey(), CONFIG_CURRENCY)) {
return NumberUtils.createLong(entry.getValue());
}
}
return null;
}
Upvotes: 0
Views: 1628
Reputation: 429
Here's a rundown of the current suggested solutions, and my thoughts on them. Note that all of these are valid solutions, so it really comes down to preference, as well as who the consumer is.
Long
and check for null
long
and check for 0
indexOf
return -1 if not found. Note that I'd prefer using -1 over 0 in this case, as 0 tends to be a valid value, while -1 tends to be an invalid one, generally. I.e. there's less cognitive load with -1 over 0 generally.Optional
generic
OptionalLong
As noted above, in most cases, I'd opt for the OptionalLong
solution, as it strikes a balance between being too object-orienty, and being too custom. I think there's arguments to move to a Currency object, which might make sense in the right project.
Also, possibly Code Review is a better fit for this question?
Upvotes: 1