• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return false or raise exception?

 
Pete Nelson
Ranch Hand
Posts: 147
Debian Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thoughts?
>
 
Matthew Brown
Bartender
Posts: 4567
8
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pete Nelson
Ranch Hand
Posts: 147
Debian Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote: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.

Sounds like a very good suggestion. First thing, I need to dig into all the subclasses of javax.naming.NamingException and see which ones should result in an Exception (like CommunicationException as a good example).

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic