DEV Community

Ahmad Salah
Ahmad Salah

Posted on

Treating Primitive Obsession with Value Objects

Primitive Obsession
Primitive values are your friends. We all start our programming journey by learning about the fundamentals types. Int, Double, String they are friendly familiar faces.
They are the default tyes we reach for whenever we are writing code and for a good reason they are convenient and we are very familiar with them.

But this obsession with the primitive types and the tendency to use to represent almost everything especially when presenting 'simple' abstractions like a measuring unit, postal code, or an email field.

What is wrong with that you might ask?

There are few issues with making primitives represent domain objects.

Wrong assumption
Take temperature as an example you might be inclined to present a temperature field as a double.
but this means you assume all double values are valid temperature values! which is wrong.

You assume that double representation is similar to temperature representation. which is wrong usually you want to limit the decimal points, add a prefix and maybe add a method to convert between Celsius and Fahrenheit.

Breaking encapsulation
When you use primitive values you will break encapsulation. how many times you will need to verify, transform or represent a type in your application?
Thinking about temperature, we might add a validation upon storing the value and again when updating it and then we will need to duplicate our logic. Now, think about all the places where you will need to display temperature you will duplicate this code!

Value Objects to the rescue
Value objects are just classes but with a couple of important features.

  1. Value Object can answer equality check
    if we wanted to represent a currency as a and later wanted to check if two points are equal. unless you are careful with your code you may get the wrong answer.
    Therefore, value objects must implement a correct equality check method

  2. Value Object should be immutable
    What we gain from delegating the equality check to the object. can lead to aliasing bugs

Aliasing as defined by Martin Fowler is "Aliasing occurs when the same memory location is accessed through more than one reference. Often this is a good thing, but frequently it occurs in an unexpected way, which leads to confusing bugs."

This can happen when dealing with value objects as we blur the lines between values and reference.

As we have seen implementing value objects requires some extra work to make your development faster you may consider using a library that helps you with that. If you are using C# I would recommend ValueOf & for Java people, you can use the @Value annotation from Lombok

Further reading on implementing Value Objects

Top comments (0)