Value Object Refactoring

After extract method or extract class introducing a value object is one of the most powerful refactorings available. A value object encapsulates a value or concept within your domain. While the term is more formally known from Domain Driven Design, DDD is not a pre-requresite for use. Introducing a value object can be applied to any code base.

Some excellent examples of value objects would include CustomerId, Money, OrderId and PhoneNumber. These could all be identified as integers, strings or decimal numbers, but doing so would lead to a series of downsides.

Making use of primitive data types to express concepts within an application is a code smell known as primitive obsession. Replacing primitives with value objects is the solution to this smell.

Primitive Obsession


The implementation of PersonalDetails would be straight forward to begin with.

Over time areas of logic can slowly migrate and move towards the class. In most IDE's, simply wrapping a primitive type as the first step can be carried out in a few keystrokes.

The constructor performs basic validation on a technical level. Once complete we can carry out any domain logic. Likewise the behaviour attached to this object (hidden for beravity) would include various domain specific logic. For example, when changing surnames any leading or trailing whitespace is removed.

One recommendation would be to expose the underlying primitive. In this example ToString has been overridden to return the string value that is being used. This should be a read only operation idealy, and enables the object to play nicely with third parties. Such use cases for this would be serialization, or writing the value to a persistent store.

Equality (and hashcode in this case) should also be implemented. This is because the nature of value objects allows them to be equal to other instances that share the same value, despite being different references in memory. The beauty of this is that value objects can be used as needed, no need for injection or other patterns.