Thursday, February 01, 2007

Say (code) what you mean

A bright, shiny object caught my eye few weeks ago while I was hiking in the snowy Cascades. Upon investigation I found a saucer shaped craft glistening in the sun. It appeared to be a space travel-capable sort of vehicle with a translucent bubble-shaped canopy that had sprung open, apparently on impact with this planet. I peered into the craft and saw a gray-green being with a large head and eyes. This being appeared to be well-frozen and so, concluding that continuing my investigation would not disturb this being, I continued to poke around the strange craft a bit more.

In what I would describe as a cockpit I found a something like a display panel which was flashing this message:

Exception in thread "nav" java.lang.ClassCastException: java.lang.Double
at NavigationWaypoint.<init>(NavigationWaypoint.java:10)
at FindWaypoint.FindNextWaypoint(FindWaypoint.java:94)
...

Obviously this sparked my curiosity! In looking around the cockpit I discovered a bit of paper--more like mylar, really--clutched in what for now I'll call the unfortunate being's hand. I liberated this piece of paper and found printing on it. I was shocked to see what the paper showed:

    7 class NavigationWaypoint

    8 {

    9     public NavigationWaypoint(Object name) {

   10         this.name = (String)name;

   11     }

   12 

   13     public String getName() {

   14         return name;

   15     }

   16 

   ...

   32     private String name;

   33 }

What a tragedy! Clearly the author of this code (presumably an inexperienced alien programmer) had errantly designed the instance constructor to take an Object rather than a String. In doing so the coder then needed a typecast in order to coerce the Object to a String in order to set the name field.

I don't know about most, but on my planet such use of a typecast is a pretty strong clue that the programmer should look around to see why the typecast is necessary; it may be indicative of a design error.

In fact, in this case it is a design error. The NavigationWaypoint class has a name field that contains a string, yet the constructor allows the caller to pass in an object of any type. This unfortunate error and the use of a typecast caused the error to manifest itself during execution of the code; obviously some other code passed in a Double rather than a String, probably a simple coding error. If the constructor had been coded to accept a String this coding error would have been caught at compile time rather than during execution, saving this little fellow the exasperation of debugging on the fly and waking up frozen on a strange planet. If only the constructor had been coded to correctly represent the type's data....

 

(This post was inspired by a true story that had nothing to do with navigation.)

 

Technorati tags: , , ,

No comments: