A few months ago, Hugh accepted a contract assignment to work on a Java project and, ever since starting, his day-to-day has felt a bit like the old game of Zork: a maze of twisty passages, all alike. So far as he can tell, a large part of the system was created by a chimpanzee (possibly orangutan) that received a treat whenever it pressed a giant button marked "Copy and Paste". One of the class files that Hugh has spent a bit of time working on has over 10,000 lines of code and at least one method that's over 2,500 lines long.

As Hugh navigated through the numerous methods like processEntry1, processEntry2, etc., he noticed an interesting pattern start to emerge.

ParentID = MathUtil.getInteger(0); // Yuck

The comment wasn't his, but certainly expressed his sentiment. The code seemed like an overly complex way of writing "ParentID = 0;" and utilized that MathUtil class that was also all over the place. Against his better judgment, Hugh dove in to the code of the MathUtil class.

public class MathUtil {
  ...snip... 

  private static final int NUM_CACHED_INTEGERS = 256;

  private static Integer[] arrCachedIntegers;

  static {
    arrCachedIntegers = new Integer[NUM_CACHED_INTEGERS];

    for (int i = 0; i < NUM_CACHED_INTEGERS; i++) {
      arrCachedIntegers[i] = new Integer(i);
    }
  }

  public static Integer getInteger(final int i) {
    return ((i >= 0) && (i < NUM_CACHED_INTEGERS)) 
       ? arrCachedIntegers[i] 
       : new Integer(i);
  }

  ...snip... 
}/

He had never quite seen anything like that before. The getInteger() method was retrieving a pre-built Integer from an array of what looks like a harebrained effort to save memory by not creating a new Integer.

Yuck, indeed.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!