It seems I sometimes create these two types of methods:
// return null on errors, and append errors to 2nd param, otherwise return result
String fetchSomething(String parameter, List<String> errorMessagesOut);
// return empty list or null on no errors, otherwise list of errors
List<String> verifySomething(String parameter);
And then the code that calls them joins the error list with the appropriate separator (for example, a comma, a new line, HTML tags ...), usually using the Apache Commons method Stringutils.join. And in the normal case there is no error, and the list will be empty.
So, I began to wonder about these two questions:
Do you see a problem returning the error message line in a list? If so, which alternative is better? (Not an exception that will cause code that calls these methods when required.)
Is it new LinkedList()or new ArrayList(0)or new ArrayList()better for a list that is expected to remain empty and that usually should only have sequential access to the iterator when it is not empty?
EDIT: Usage Example:
List<String> verifyParameters(JSONObject params) {
List<String> ret = new ArrayList<String>(0);
if (!verifyKey(params.get("key")))
ret.add("Invalid key: " + key);
if (!verifyAccess(params.get("user"), params.get("pass")))
ret.add("Authentication error");
return ret;
}
...
List<String> errors = verifyParameters(params);
if (!errors.isEmpty()) {
connection.sendErrorListMessage(errors);
logger.warn(StringUtils.join(errors, ", "));
controlPanel.show("Errors: \n- " + StringUtils.join(errors, "\n- ") + '\n');
throw new AbortException("invalid params); // or maybe return false/null;
}
// proceed with valid params
Usually error list processing will not have all of them, it just tries to illustrate the point at which the error list is a list of messages intended for people, regardless of how it will be shown, and also not related to / useful for handling different errors differently.
source
share