People. Software.

Improving Code – Remove “Primitive Obsession”

One of the best ways to improve code is to remove cases of Primitive Obsession. This particular code smell arises when we use primitive types (such strings or integers) to represent what should be explicit types in our domain.

In some cases, primitive types are quite appropriate. For example, we may only need an instance of some string to display somewhere in our UI. However, in other cases, our “simple string” should be a better abstraction within our domain.

For example, using a string to store my name (“Chris Melinn”) would likely be a loss of an abstraction. This probably needs to be modeled as a something more explicit such as a User or a Person, having a FirstName and a LastName. This is particularly true when other places in the application do things such as parse this string to derive a first name and a last name. These behaivors are telling us that our “name” is trying to be more than just a string.

At first, it may seem silly to create a whole new class that possibly contains just one or two members (like our Person with a Name or FirstName and LastName). However, by creating this “placeholder”, we are defining its place in our domain. More importantly, you may find that other behavior begins to find its way into your “simple” class (such as the conversion and calculation logic that would otherwise be spread around your application). When this happens, you know you did the right thing.

For a much better description and discussion, please take the time to watch this video by Corey Haines and J.B. Rainsberger. They are both excellent craftsmen, and, if you haven’t already, I recommend you take the time to explore their blogs as well.

Post navigation

6 thoughts on “Improving Code – Remove “Primitive Obsession””

You’re right. Code is much easier to read and debug when I have to dig through hundreds of classes for twice-used abstractions to find just how every function that could have caused the bug may have been implemented.

Sean, with modern tools this takes very little time. Additionally, when things are better defined and well named, it speeds up debugging and requires less navigation of code. Additionally, with good unit tests and well designed classes, digging through “hundreds of classes” seems very unlikely.

Try it out and see what you think. I think you’ll discover its incredibly difficult, if not impossible, to really take things too far in good domain modelling.