Primitive Obsession

Chris Wheeler has posted a very nice blog entry on the Primitive Obsession code smell. Primitive Obsession is one of my favorite smells as well: it's easy to spot, easy to fix, and yields some really great designs when thoroughly stamped on. (In case you don't remember, Primitive Obsession is when you use basic types, like 'int,' instead of creating a class, like 'ID' or 'Age'.)

Did I say easy to spot and fix? It is, but it's also an easy one to let slip by. And once Primitive Obsession has been around for a while, it's a real bear to get rid of. Changing one parameter leads to this horrible cascading effect and (if you're me) embarrasing refactoring meltdowns.

If Primitive Obsession is so easy to see and fix when caught early, why do we let it go? I have a couple of theories. First, it feels silly to make a class that just renames a primitive:

public class Age {
  private int age;

  public Age(int age) { this.age = age; }
  public int toInt() { return age; }
}

Lame, huh? Second, using Primitive Obsession is like being seduced by the Dark Side. "I'm only dealing with people's ages in this one method call. No need to make an (oh so lame) Age class." Next thing you know, your Death Star is getting blown up by a band of irritating yet plucky and photogenic youngsters.

Best way I know to deal with it is to get over the aversion to creating small classes. Once you have a place for a concept, it's amazing how you find opportunities to fill it up. That class will start small today, but in no time at all it'll be all grown up and asking for the keys to the family car.

If you liked this entry, check out my best writing and presentations, and consider subscribing to updates by email or RSS.