The sad case of the Java object that couldn’t be instantiated in Java

Today’s code blooper involves a Java object that cannot be instantiated in Java.
I was helping somebody unit test some code and we kept getting a null pointer exception on the constructor. First of all, the object in question had overly complicated constructors. Imagine something like this.
public FruitBasket(){
// Does nothing important
}
public FruitBasket(String ownerName, Fruit[] fruits, Color color, String brand, Date purchaseDate, boolean hasLid, boolean hasHandles, boolean hasLock, int maxFruits, int width, int height) {
// Copies all values, and copies array to a local array (does not keep reference to one in parameters)
}
Now imagine that constructor has 12-14 parameters, and 1 more constructor. It’s begging for some factory, or heck, just using an empty constructor and rely on “set” methods. Anyways, the thing was blowing up in the constructor and it was hard to see why. It was when it was copying the array to the array in the object. After a bit of debugging I noticed that the array was never initialized, so it was trying to reference a null array. Doh! OK, but this code runs in a real product, how could this work at all?
The answer? JNI. The object in question usually gets created by a JNI program. The array is created in the JNI code, which has full access to the Java private fields, so it’s not a problem. The irony is that without fixing this class, it can never be created in Java. I thought that was a bit ironic, but what this really shows is that this class is lacking basic unit testing in the first place. During integration test, you won’t see these problems because every bit of the application is doing its job. But when you apply unit tests, you tend to catch things like … not being able to instantiate the class!
The bug is a common mistake, but the biggest problems are having multiple constructors share zero code, long constructors that are only large because people keep adding features, and zero unit testing for core classes that are used all over the place.
Filed under: Code Bloopers on May 4th, 2007

Leave a Reply