Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defensive Programming: Guidelines in Java

I’m from a .NET background and now dabbling in Java.

Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough):

public void setTokens(Node node, int newTokens) {
    tokens.put(node, newTokens);
}

However, this code can fail for two reasons:

  1. User passes a null node.
  2. User passes an invalid node, i.e. one not contained in the graph.

In .NET, I would throw an ArgumentNullException (rather than a NullReferenceException!) or an ArgumentException respectively, passing the name of the offending argument (node) as a string argument.

Java doesn’t seem to have equivalent exceptions. I realize that I could be more specific and just throw whatever exception comes closest to describing the situation, or even writing my own exception class for the specific situation.

Is this the best practice? Or are there general-purpose classes similar to ArgumentException in .NET?

Does it even make sense to check against null in this case? The code will fail anyway and the exception’s stack trace will contain the above method call. Checking against null seems redundant and excessive. Granted, the stack trace will be slightly cleaner (since its target is the above method, rather than an internal check in the HashMap implementation of the JRE). But this must be offset against the cost of an additional if statement, which, furthermore, should never occur anyway – after all, passing null to the above method isn’t an expected situation, it’s a rather stupid bug. Expecting it is downright paranoid – and it will fail with the same exception even if I don’t check for it.

[As has been pointed out in the comments, HashMap.put actually allows null values for the key. So a check against null wouldn’t necessarily be redundant here.]

like image 796
Konrad Rudolph Avatar asked Sep 18 '09 12:09

Konrad Rudolph


1 Answers

The standard Java exception is IllegalArgumentException. Some will throw NullPointerException if the argument is null, but for me NPE has that "someone screwed up" connotation, and you don't want clients of your API to think you don't know what you're doing.

For public APIs, check the arguments and fail early and cleanly. The time/cost barely matters.

like image 197
Ken Avatar answered Sep 21 '22 10:09

Ken