Tuesday, 6 May 2008

Code Horror Zwei

I came across this piece of code poetry today and laughed.

...
Date currDate = new Date(); 
Date expDate = null;
int array[] = new int[3 ]; 
   
if(expirationDate != null && !"".equals(expirationDate)){
    int i = 0;
    StringTokenizer st = new StringTokenizer(expirationDate,"/");
    while (st.hasMoreTokens()) {
        array[i++] = Integer.parseInt(st.nextToken());		
    }

    expDate = new Date(array[2 ] - 1900, array[0 ] - 1, array[1 ]);
    int x = expDate.compareTo(currDate);
    if(x <= 0) {
        rd.forward("landingnotfound.html");
    } 
}
...

It took me a half-hour to figure out what the developer was doing: compare two dates and determine if one was before the other. How he got to the above is lost to his fever dream.

Here's how I refactored this horror...

...
Date currDate = new Date(); 
Date expDate = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
   
if(!"".equals(expirationDate)){
    expDate = df.parse(expirationDate);
    if(currDate.after(expDate) {
        rd.forward("landingnotfound.html");
    } 
}
...

At some point in our conversation, I think he said, “It works.” ~o)

Posted by caffeinated at 10:23 PM in nerdery
« May »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031