Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 203

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

$
0
0

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


Viewing all articles
Browse latest Browse all 203

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>