Tutorials

Design Patterns - Value Object

by John Kleijn on Oct 9, 2008 7:26:24 AM

Solution

In Patterns of Enterprise Application Architecture, Martin Fowler makes a clear distinction between ‘reference objects’ and ‘Value Objects’. His short definition of a Value Object:

“A small simple object, like a money or date range, whose equality is not based on identity.”

The key being the equality. Normally, all objects persist and have their own identity, ignorant to equality of their content. An object should be a Value Object if it it’s equality is not based on identity, but on it’s ‘value’. If it is safe to equal óne hundred kudos to another hundred kudos, a Value Object – possibly called ‘Kudos’ - is warranted.

The below code is a scenario in which a Value Object is needed:

You probably already noticed that problem is that we are both using the same Nails object. In this case the problem may be easy to spot and avoid, but as your application becomes bigger, preventing this type of mishap can save you a huge headache. Another mayor benefit of using Value Objects is they enable you to encapsulate type-specific operations. Martin Fowler does a great job at demonstrating this with his Money pattern, which encapsulates the handling of rounding currency.

The key to creating Value Objects is making them immutable. Because Value Objects’ equality don’t depend on their identity, simply creating a new object when the value changes, accomplishes this:

Now that Nails is immutable, the client code needs to be adapted also. Since the value of the object in the $screws property can not be changed, we’ll have to reset it instead:

That's all there is to it.

Comments

Good topic.

1. Josh Robison on Dec 2, 2008 8:25:00 PM
Login or register to post a comment.