javaexceptionreturn-value

Best way to return status flag and message from a method in Java


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 authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:

Any other suggestions?

Edit Missed this option off

Edit Solution:

I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.


Solution

  • 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.