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
I personally think creating a new class called AuthenticationStatus with the boolean and the String is the most Java like way. And while it seems like overkill (which it may well be) it seems cleaner to me and easier to understand.
Is this the only method where you have such a requirement? If not, just generate a general Response class with an isSuccessful flag and a message string, and use that everywhere.
Or you could just have the method return null to show success (not pretty, and does not allow returning a success AND a message).
Successful authentication should be the "normal" case, so an authentication failure is the exceptional case.
What are the different status strings for the user anyway. I can see only two, success or failure. Any further information is a potential security issue. Another advantage of the solution with exceptions is that it cannot be called in the wrong way and the failure case is more obvious. Without exceptions, you write:
if (authenticate()) {
// normal behaviour...
}
else {
// error case...
}
You can accidently call the method ignoring the return value. The "normal behaviour" code is then executed without successful authentication:
authenticate();
// normal behaviour...
If you use exceptions, that cannot happen. If you decide to not use exceptions, at least name the method so that it is clear that it returns a state, e. g.:
if (isAuthenticated()) {
//...
}
Instead of creating a special object for return type, I usually just return an array where all the returned information is stored. The benefit is that you can extend this array with new elements without creating new types and mess. The downside you have to know exactly what elements should present when array is returned from particular method to parse it correctly. Usually I agree on certain structure, like first element is always Boolean indication success, second is String with description, the rest is optional. Example:
public static void main(String[] args)
{
Object[] result = methodReturningStatus();
if(!(Boolean)result[0])
System.out.println("Method return: "+ result[1]);
}
static Object[] methodReturningStatus()
{
Object[] result = new Object[2];
result[0] = false;
result[1] = "Error happened";
return result;
}
I would choose the Exception option in first place.
But, in second place, I would prefer the C-style technique:
public boolean authenticate(Client client, final StringBuilder sb) {
if (sb == null)
throw new IllegalArgumentException();
if (isOK()) {
sb.append("info message");
return true;
} else {
sb.append("error message");
return false;
}
}
This is not so strange and it's done in many places in the framework.