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

Draemon picture Draemon · Dec 10, 2008 · Viewed 26.6k times · Source

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:

  • Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it.
  • Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional.
  • Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method.
  • Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there.

Any other suggestions?

Edit Missed this option off

  • Return null for success - Is this unsafe?

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.

Answer

Ashley Mercer picture Ashley Mercer · Dec 10, 2008

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.