Eliminate Primitive Obsession

This post was imported from blogger, to see the original, likely better-formatted post see kalebpederson.blogspot.com.

>Primitive obsession is not just fiddling bits, playing with ints, or tossing around chars. Primitive obsession is using something non-expressive where something better suited is possible. It’s about using List and Enum when domain objects would be far better.

In my post “The UI/UX Difference” I mentioned implementation models — a system wherein the implementation leaks through to the user, forcing the user to understand something about how the system is implemented before it becomes usable. It turns out, I’ve been doing the same thing in my code.

Primitive: “1.a – not derived, 2.c – belonging to or characteristic of an early stage of development

I’m guilty. My code has too often been nothing more than a code implementation model. How’s that you might ask?

Let me explain. Consider the following code:

createUri(
    annotation.getArgument(2)
        .getString(AnnotationConstants.SeparatorDefault)
    )

So now, my question to you — what does that code do? You probably can’t tell me. What if I had written the following:

separatorAnnotation.separatorStringOrDefaultValue().asUri()

The above code should make it much more obvious — it’s converting the separator string, or its default value, in URI form.

The first form uses a general annotation object, one that isn’t derived enough. It forces the user, in this case a programmer, to:

  • know that the separator string is the third argument in the annotation, and 
  • know that each argument is an argument object, and 
  • know that the argument object can be converted to different types, and 
  • know that the argument should have been a string type, and 
  • know where the default value for that annotation parameter was specified.

That’s bad, horrible, and awful! I’m forcing all these things upon other programmers because I’m failing to work with domain-level objects.  In this case, the separator annotation is a fundamental part of my domain and my business.  And yet, by working with a generic annotation object, I left it a primitive.  I left it in an early stage of development.

Don’t make the same mistake I did.  Primitive obsession is much more than using a bunch of ints, it’s about avoiding your domain in code. Use domain code and free others from understanding the implementation.

No comments yet.

Leave a Reply