I have a deceptively simple scenario, and I want a simple solution, but it\'s not obvious which is \"most correct\" or \"most Java\".
Let\'s say I have a small authe
You could return a Collection of error messages, empty indicating that there were no problems. This is a refinement of your third suggestion.
Return the Object. It allows you to put additional functionality into the Class if you need it. Short lived objects in Java are quick to create and collect.
There are a lot of good answers here so I will keep it short.
I think failure of a user to authenticate can be considered a valid case for a checked exception. If your style of programming favoured handling exceptions then there would be no reason not to do this. It also removes the "How to return multiple values from a method, my method does one thing It authenticates a user"
If you are going to return multiple values then spend 10 minutes creating a generic PairTuple (can also be more than a pair TripleTuple, I won't repeat the example listed above) and return your values that way. I hate having small dto style objects to return various multiple values they just clutter the place.
You could use exceptions....
try {
AuthenticateMethod();
} catch (AuthenticateError ae) {
// Display ae.getMessage() to user..
System.out.println(ae.getMessage());
//ae.printStackTrace();
}
and then if an error occurs in your AuthenticateMethod you send a new AuthenticateError (extends Exception)
I would most probably go for something like :
class SomeClass {
public int authenticate (Client client) {
//returns 0 if success otherwise one value per possible failure
}
public String getAuthenticationResultMessage (int authenticateResult) {}
//returns message associated to authenticateResult
}
With this "design", you can ask for a message only when authentication fails (which I hope is the scenario that occurs 99,99% of time ;))
It may also be of good practice to delegate message resolution to another Class. But it depends of your application needs (mostly, does it need i18n ?)
Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this.
Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long as the return values are clearly explained in the javadocs there shouldn't be any confusion.