Exceptionally Bad Code

If there's one Java programming idiom I hate more than any other it's the "ignore null" idiom practiced by some Java programmers. Briefly:
Exceptionally Bad Code
public method(Foo bar) {
  if(null != bar) {
     //  Some operation upon bar
     ...
  }
}

This is a pretty common sample. method() has special handling for bar being null. When bar is null the method has no effect. This is almost certainly evil. Unless method() considers null to be valid input and really does want to act differently based upon a null input value then choosing to ignore null inputs merely masks a problem elsewhere.

Ignoring bad input in this way ignores the principle of failing as close to the source of the problem as possible. Finding the root cause of strange behavior when the "ignore invalid inputs" idiom is used is much more difficult than when bad input causes errors. Don't be afraid of generating exceptions for bad input and/or allowing NPE exceptions to be thrown on your behalf by the JVM when called with bad input. The sooner the bad input is identified, the sooner the programmer looking at the problem can find the source of the error.

I've run into a corresponding problem in loosely coupled APIs such as web services. This is the problem where the web services API returns a 200 result no matter what input it is provided. Yes, it will provide correct results when provide the correct input but it will also happily provide (usually irrelevant) results when provided bad input. This also violates the principle of failing as soon as possible and makes problems a lot harder to diagnose. Because of the decoupling of systems this type of problem can be even harder to diagnose than the "ignoring null" problem.

Generating errors or exceptions is the correct response to your code receiving bad input. Intentionally ignoring invalid inputs is not a good strategy for any system especially when multiple programmers or modules are involved.

Comments:

Yes! And when you throw that exception for bad input don't forget to put useful information in it:
http://bugs.sun.com/view_bug.do?bug_id=4951780

Posted by Joseph Dipol on January 27, 2010 at 09:09 AM PST #

Post a Comment:
Comments are closed for this entry.
About

mduigou

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today