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

后端 未结 17 1117
清酒与你
清酒与你 2020-12-25 12:55

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

相关标签:
17条回答
  • 2020-12-25 13:22

    You could return a Collection of error messages, empty indicating that there were no problems. This is a refinement of your third suggestion.

    0 讨论(0)
  • 2020-12-25 13:22

    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.

    0 讨论(0)
  • 2020-12-25 13:23

    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.

    0 讨论(0)
  • 2020-12-25 13:25

    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)

    0 讨论(0)
  • 2020-12-25 13:28

    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 ?)

    0 讨论(0)
  • 2020-12-25 13:29

    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.

    0 讨论(0)
提交回复
热议问题