I want to write a method in Java that checks that some conditions are stored on some data, and confirms that the data is valid or generates the corresponding error message otherwise.
The problem is that we cannot return more than one method from the method, so I wonder what is the best solution (in terms of readability and maintainability).
First decision. Easy, but we can’t know what exactly made us check:
boolean verifyLimits1(Set<Integer> values, int maxValue) {
for (Integer value : values) {
if (value > maxValue) {
return false;
}
}
return true;
}
The second solution. We have a message, but we use exceptions in such a way that we should not (besides, probably, this should be a domain dependent exception, too many service IMOs):
void verifyLimits2(Set<Integer> values, int maxValue) {
for (Integer value : values) {
if (value > maxValue) {
throw new IllegalArgumentException("The value " + value + " exceeds the maximum value");
}
}
}
. , : , ( javadoc).
String verifyLimits3(Set<Integer> values, int maxValue) {
StringBuilder builder = new StringBuilder();
for (Integer value : values) {
if (value > maxValue) {
builder.append("The value " + value + " exceeds the maximum value/n");
}
}
return builder.toString();
}
? (?)?
(: , , Collections.max(values) > maxValue ? "Out of range." : "All fine.": -).)