Three Java Pitfalls

A coworker asked for a few gotchas in Java; things you just step your foot into and never saw coming.  Three seemed a good number of things to list off at once, and they're three that have come up recently.

The time and date libraries in Java are a bit broken; getting the values you want usually takes a couple lines of code, and things like time zones aren't well represented.  There are inconsistencies you get somewhat used to (getTime vs getDate returning milliseconds and the day of the month, respectively), trying to represent dates before 1970 can't work, and the Calendar implementations add a whole new level of odd choices.

Joda Time is a full replacement for java.util.Date and all of the implementations of java.util.Calendar, and sidestepping some of java.sql.Date.  It's likely to be the java.util.Date replacement starting with Java 7, if Java 7 makes it to developers any time soon.  In the meanwhile, just use the library, and save the headaches.

I've been waging a war in our codebase to *always* have developers use braces, even on one-line code blocks.

if (true) 
    System.out.println("print this"); 
    // And this comment here makes this a bit more confusing    
    else {         // Bad indentation might make it worse
    System.out.println("not true"); 

Becomes a lot more clear if *every* if/else result must have braces.
if (true) {     
    System.out.println("print this"); 
}  else {           
    // Bad indentation might make it worse.         
    System.out.println("not true"); 

The reasonable counter-argument  is that code on one line shouldn't need braces:
if (true) System.out.println("print this"); 

However, Ctrl-Shift-F in Eclipse autoformats code, and I'd recommend it, but it tends to reformat that back to two lines, breaking the original rule.

Finally, I suggested that learning which data types are synchronized goes a long way.  Synchronized code will often be significantly slower; unsynchronized code won't be thread safe.  It might have been better had the classes been ArrayList and ArrayListSynchronized, instead of ArrayList and Vector, but it is what it is.

The other half of synchronized data types is that some types don't have a 1:1 replacement in the standard API; you need to go to third party libraries for that.  SimpleDateFormat isn't thread safe, and it's replacement, FastDateFormat, is in Apache Commons Lang. 

At that point, I realized that *all* of Apache Commons is pretty much a must-read for this question, and recommended the online reference The Common Java Cookbook, on   It's a step by step methodical walkthrough of *all* of Apache (formerly Jakarta) Commons, and it's great for finding small parts of their  work that you might have missed before.

No comments: