Dave was recently asked to write up documentation for a newly inherited system in preparation for a big rewrite. As is standard industry practice, the original developer no longer works for the company, leaving Dave high and dry if he runs into any problems.

What Dave found was an incredibly over-engineered codebase with patterns applied for their own sake and copious amounts of comments that failed to convey anything important about "why" the code did anything.

Among the gems he discovered was the zip code cache that stores "immutable" ZipCodeInfo objects:

/**
 * Contains various information relating to zip codes.
 */
public class ZipCodeInfo implements ImmutableZipCodeInfo {
  private String zipCode;
  private String state;
...
  //--------------------constructors--------------------//
  public ZipCodeInfo(String zipCode, String state) {
    this.zipCode = zipCode;
    this.state = state;
  }

  //--------------------public methods--------------------//
  public String getZipCode() {
    return zipCode;
  }
  
  public void setZipCode(String zipCode) {
    this.zipCode = zipCode;
  }

  @Override
  public int hashCode() {
    final int prime = 42;
    int result = 1;
    result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode());
    
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (obj instanceof ZipCodeInfo) {
      return false;
    }
    
    return Equal.equals(this.getZipCode(), ((ZipCodeInfo) obj).getZipCode());
  }
}

Thankfully, the ZipCodeInfo implemented equals() and hashCode() as it should, so that the next piece could exist:

public class ZipManager {

  private Map<ImmutableZipCodeInfo, WeakReference<ImmutableZipCodeInfo>> zipCache = new HashMap<can't wait for java 7>();
  private final ZipCodeInfo ZIP_INFO;

  ...

  //--------------------public methods--------------------//

  /**
   * Returns zip code information regarding the given zip code.
   * 
   * @param zipCode the zip code
   * @return the zip code information for the zip code
   */

  private ImmutableZipCodeInfo getZipCodeInfo(String zipCode) {
    ZIP_INFO.setZipCode(zipCode);
    if (zipCache.containsKey(ZIP_INFO)) {
      return zipCache.get(ZIP_INFO).get();
    }
    
    ZipCodeInfo newZipInfo = loadZipCode(zipCode);
    zipCache.put(newZipInfo, new WeakReference<ImmutableZipCodeInfo>(newZipInfo));
    
    return newZipInfo;
  }
}

What a great idea! The hashing mechanism that the built-in-and-used-by-millions HashMap class uses can't possibly be good enough to handle a simple string. Add a(nother) layer of indirection via setting a value on an "immutable" class and using that to look up the desired object. Amazing!

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