This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am working on a utility library to handle group-based authentication. I have a method that first checks a user's credentials, and then checks to see if they are a member of a particular group. My first "good enough to work" attempt is as follows:
What I am not sure of, is it better to simply return false on failure, or should my method throw an exception? It seems like returning false would be a lot simpler to use, but less informative when things went wrong. We use log4j almost religiously, so we could still get the exception info postmortem.
In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower
The question is, is failing an exceptional condition?
In the event of it failing because you couldn't connect to the LDAP server, or something like that, then I'd definitely throw an exception. That allows the calling code, which has a much better idea of the context, to decide what to do. It might want to treat it as if it was false, it might want to show an error message, it might want to throw the exception further up the stack. This method is too low level to know what ought to be done.
The less clear-cut case is what do to if there's no error, but the user isn't found, or if the password isn't recognised. In that case I'd say "it depends". Should the client code know whether the user exists before calling this method or not? If yes, then it should know not to call it. In that case I'd throw an exception if not found. In effect this means the existence of the user is a pre-condition of the method. If no, and this method is intended to determine whether the user exists or not, then using a return value is fine. Similarly for the existence of the group, and checking the membership.
Without knowing the exact requirements, I'd guess my approach would be to throw an exception if the user or group doesn't exist, and reserve the return value for indicating whether they're a member of the group or not.