To what extent should one make exceptions redundant or atomic to a method.
For instance, suppose I have a method public void authenticate(String username, String password)
that calls private void invokeServer(String username, String password)
.
Both methods require those params to be non-zero length, and as such I would raise a NullPointerException
if needed. Should I sanity check in invokeServer
as well as authenticate
on the basis that it could potentially be used independently at a later date?
First of all, non-empty and NullPointerException
are two different beasts, so you should definitely not throw a NPE for a non-null empty string.
In general, it makes sense to think about your exceptions on a higher level than just the null/non-empty-kind of level. In your case, you are taking about a username
, or even more general, when you combine the two attributes you are talking about Login Credentials. And lo and behold, both of your methods in one way or another deal with login credentials, so a InvalidLoginCredentialsException
or some such nicely fits both places (and probably others as well).
When you think about the error cases from the viewpoint of your business or customers, by assigning use-cases or domains (or any fancy word like that, which is currently en vogue), then you should have a much easier time to deduce exceptions at a useful granularity level.
3
Short version
In your case one check should be enough. In which method depends on your code and coding-guidelines.
Long version
First of all, you need to sanity-check input on the server. If there is a problem, the server should throw a BusinessException
(with an appropriate message).
On the client side, you have two options:
- give it a try, send the input to the server, and present the potential error to the user.
- sanity-check the input-values to tell the user something’s wrong even before sending data to the server (e.g. in JSF you can register validators for components).
Finally, you still have to cope with the potentially thrown BusinessException
s on the client side, because it is possible that the input seems valid but the server still reports an error. Therefore you should implement some kind of GeneralErrorHandler
on the client, which catches any uncaught exceptions and presents them in a human readable way.
(Keep in mind, that the user’s language may differ to the one of the exception-message.)