The S#arp framework: using value objects

If you’ve been involved with DDD, you have surely built several value objects. But what is a value object? Eric Evans defines it (in his seminal work) as being an object which doesn’t have a conceptual identity and that is used for describing a characteristic of a thing. As always, there really isn’t any good rule for identifying value objects since it all depends on the *context* (some objects will be value objects in a context and entities in another).

In practice, value objects are immutable. This means that you’ll end up with objects that need to receive all the necessary values during construction time. If you need to change any of those values, then you’ll need to create a new instance since these objects don’t expose any public setters. Typically, you’ll also want to customize operators == and !=. The S#arp framework introduces a class that takes care of all this boilerplate code. We’re talking about the ValueObject class.

This class extends the BaseObject class and implements the GetTypeSpecificSignatureProperties in a very similar way to what we did in the previous post (the difference is that it ensures that none of the properties are annotated with the DomainSignatureAttribute attribute– more about this in the future). Besides introducing a default implementation for the previous method, it will also introduce custom implementations of the == and != operators (which end up delegating to the Equals method inherited from the base class).

To illustrate the usage of this class, we’ll change the example presented in the previous post and implement SimpleAddress as a value object. Here’s the changes we need to make to the SimpleAddress class:

public class SimpleAddress:ValueObject {   
   public SimpleAddress(String street, String zipCode) {
            Street = street;
            ZipCode = zipCode;
   public String Street { get; private set; }
   public String ZipCode { get; private set; }

And that’s it. The changes were minimum and most (if not all) of them are needed to ensure proper immutability. Notice that ensuring immutability of the properties used on the hash calculation is a must for ensuring the correct behavior of our objects (especially if they’re kept on hash tables collections).

And that’s it for today. More about the S#arp framework on the next posts.


~ by Luis Abreu on April 18, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: