A Discussion on Domain Driven Design: Value Objects

 

In my previous post we talked about Entities. Entities have a lot of overhead associated with them. They have a full lifecycle from cradle to grave. They also have identity which forces the domain model to be very expressive in tracking and coordinating their transient states. It would be great if we could compositionally break up the Entity into smaller objects that form descriptive attributes of the Entity itself but don’t have identity. Luckily for us these sometimes smaller objects are referred to as Value Objects in Domain Driven Design.

NOTE: It is important not to confuse a Value Object with a CLR value type. Value Objects are unaware of the actual programming language. They are high level modeling concepts that lend themselves to elucidating greater incite of the Domain Model. Don’t assume that an int, string or double are Value Objects.

Take a look around you I bet you have a container of pens or pencils all with varying tips and colors. You have a pack of gum nearby filled with individual pieces of gum. Looking in your desk you have a container of paper clips of varying size and shape. If you are wearing a pair of sneakers hopefully you have a pair of shoe laces. Let’s consider your wallet, I bet you have currency of some kind in there with varying denominations of value. In the world of DDD we refer to all these objects as Value Objects. Why because we don’t care about the identity of these objects in the context of day to day activities. We don’t care about each individual paperclip when you need to hold papers together, we just care that there are paper clips. When I put on my Nike’s I don’t care about the shoe laces outside of the context of the shoes themselves. If the laces wear out, I simply replace them with new laces not once giving any consideration to the old laces. I don’t look at the old shoe laces, look up their model number and try to find the exact same model number manufactured from the Nike factory.

If I had to give you one rule of a Value Object vs. an Entity it would simply be this.

“A Value Object cannot live on its own without an Entity.”

But I think Eric Evans does a better job at describing Value Objects.

“An object that represents a descriptive aspect of the domain with no conceptual identity is called a VALUE OBJECT. VALUE OBJECTS are instantiated to represent elements of the design that we care about only for what they are, not who or which they are.” [Evans 2003]

I am going to ask you again to hang up your developer or analyst hat and simply read what I am about to write. Try not to apply any pre-dispositional ideas that you have gained through experience. Don’t apply what you do at work. Work with me here!

My son’s name is Jay. Jay is 10 years old and goes to school. I really care about Jay, I want to make sure he is safe and I need to know his whereabouts at all times. When I wake up Jay in the morning, he knows that I expect him to brush his teeth, comb his hair and put on his clothes for school. Being a Dad I don’t really care what type of clothes he wears, just as long as they are appropriate for school. So Jay has to make sure he is wearing a tee-shirt, pants and shoes. Let’s stop right here. Let’s model this scenario in a Domain Model.

As you can see the Jay Entity mimics the structure that we described above. But let’s talk a little bit about what Jay means to me. Jay has hair and teeth, which is what Jay is to me. His tee shirt, pants and shoes are important to me but they are not Jay. How can we make the model more expressive yet take the attributes of shirt, pants and shoes and still have meaning to me? How about the following model?

As you can see I went ahead a created the Attire type. The model is still contains enough information that I have not lost the expressive whole of the Jay Entity having a Tee-Shirt, Pants and Shoes. Since I have taken this path, I have allowed the Jay Entity to have a simpler compositional structure within the domain model. Now if you were paying attention you noticed that I gave Jay an SSN. After all doesn’t he have one? Isn’t this how I could distinguish Jay from other sons or daughters I may have? NO!!! Remember Jay is an Entity and Entities have identity. How do they have identity? They have identity based on the context of the domain model not what the developer or analyst deems necessary to distinguish Jay from the rest of my family. In your family do you call you son, daughter or brother, by saying “Son 000-52-9899 please pick up the trash.” No you simple say “Jay can you please pick up the trash.” So within the domain of my family what makes Jay unique? Within my family how can I guarantee that when I call for him, he will come? I hope you guessed that his name is his identity. Yes it is that simple, his name. Remember YAGNI, well that applies in domain modeling as well don’t complicate the model by coming up with attributes that mean something to the developers but nothing to the customer. So for the sake of time I am going to speed up the modeling here to show you more of my family domain.

So here is a more refined model. Talking to myself I discovered that I also have a daughter. So the Jay type didn’t give me near the flexibility that I needed. Now I have and general Kid Entity that I can use for either my son or daughter. I digress, going back to Value Objects. Here is a general question you can ask yourself when you are evaluating your model. “Can the Attire type exist without the Kid type in the given context of the domain?” Meaning from an architectural stand point are you ever going to ask the attire, “Who do you belong to?” Maybe in some other context you could, say for instance a dry cleaning application. Yes I would have to agree that the Attire type, such as a suite, may exist on its own and have its own ID. Then I would have to use the Attire type to figure out what customer it belonged too. But in the family context, No! The Attire cannot exist on its own. It is a Value object of the Kid Entity. In fact in order for me to access the Attire or change anything on the Attire I should have to go through the Kid. This concept of ownership and responsibility is called an Aggregate in DDD. We will talk about that on a later post.

As you can see Value Objects are simple in nature but for a reason that still eludes me, are a difficult concept to master in practice. Entities and Value Objects work in tandem to produce a very fluid model. Please don’t get discouraged if you have hard time figuring out what is what. Remember to take a step back and stop thinking like a developer. Talk through the model as if you were the product owner. Usually the Entities and Value Objects pop right out when you do this. Question yourself, “Does this object need identity outside of this object?” “Can I simplify this object by creating a Value Object?” When you answer these questions make sure to put the model in front of the product owner so that they may validate your refactoring. Your model is the code, your code is the model, never forget that. The two must grow organically together and still capture the business domain from the product owner’s perspective. But what if I have an object that isn’t an Entity or a Value object, well this friend is my next post. Services…

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Joe Ocampo

My personal philosophy is simple: "Have a good strategy that sets the environment for success through the enablement of the whole. Be agile but with a mind towards pragmatism. Delegate to the best qualified individuals, but don’t be afraid to involve yourself in all parts of a job. Treat everyone with respect, humility, and with a genuine pursuit towards excellence." Respected business and technical leader with expertise in directing organization towards effective results driven outcomes. Proven ability to perform and communicate from both technical and business perspectives. Strong technical and business acumen developed through experience, education and training. Provides the ability to utilize technology, harness business intelligence and execute strategically by optimizing systems, tools and process. Passionate about building people, companies and software by containing cost, maximizing operational throughput and capitalize on revenue. Looks to leverage the strengths of individuals and grow the organization to their maximum potential by harnessing the power of their collective whole and deliver results. Co-Founder of LosTechies.com
This entry was posted in Domain Driven Design (DDD). Bookmark the permalink. Follow any comments here with the RSS feed for this post.

35 Responses to A Discussion on Domain Driven Design: Value Objects

  1. jmeridth says:

    I understand you wanted us to stop thinking like a developer and I understand a domain item can either be an entity or a value object based on context, but in a code base where the item already has identity and is being persisted, but in the current context it is a value object, does a developer remove the value object’s prior entity identity and replace it with it’s new “parent” entity’s identity value?

    i.e.,
    1st Context:
    wallet.id = 100; (entity)

    2nd Context:
    person.id = 200; wallet.id = ? (value object)
    should the wallet utilize parent’s identity value or still follow the code base and retain it’s own identity value? Of course I realize database storage can play a role here, but I’m wondering from a domain model perspective.

  2. JoeyDotNet says:

    I’ve had the same kind of questions, Jason. Still learning a lot about DDD myself, but I think the answer relates to Aggregates. Joe? :)

    Speaking of, I’m really looking forward to when you get to Aggregates, as that seems to be the toughest one for me to apply right now. The concept in itself is pretty easy, but being able to identify them and apply it is totally different.

    Looking forward to more DDD goodness… :)

  3. agilejoe says:

    I was waiting for this question to come up. I was trying not to answer this because, well, it depends.

    Context is one of the most important attributes of your model. Context defines intent and behavior of your objects. Without it you are simply creating types with no rhyme or reason. Sure you may have test converge but do you even know why the object is being created and behaves the way it does. For the most part, No.

    I am going to talk about this in a later post but the answer to your question is Boundary Context. If you have a small application by small I mean (small application < enterprise application. With my son it is easy he doesn’t really care what he is wearing he simply puts on his cloths. But my daughter on the other hand is very methodical in her approach. Given that my daughter is getting dressed the Attire Value Object becomes an Entity. This is how it transforms. My daughter had a huge closet filled with many shirt, skirts, pants, blouses etc. In her world she has very distinct outfits that have to go together. For instance there is the Hello Kitty blouse with matching skirt and spring hat combo. There are also the outdoor playing outfits. The point I am trying to make is that to my daughter the Attire type has identity. Its lifecycle is influenced by the change in season. Those of you that have daughters completely understand what I am talking about.

    So you see in the context of my son the Attire type is simply a Value Object but in the context of my daughter it receives identity and becomes an Entity. From an architectural perspective you may use the template pattern to create a base Attire type from which my daughter’s Attire Entity type can be derived based on the context (state) of who is getting dressed.

    By the way this response does nothing to explain the true potential of the Boundary Context.

    Cheers!

  4. jmeridth says:

    JoeyDotNet,
    I agree that the aggregates do play a role and context is the governing concept. I understand the theoretical side of DDD, I was just wondering out loud for any person doing the application. I do agree that in a non-enterprise application there is a good chance that the migration between the DDD elements won’t happen.

    I haven’t gotten to the part in the book about Bounded Contexts (Chapter 14 of Evans book). I’m reading it VERY slowly to understand it.

    I agree. Joe, keep the DDD goodness coming.

  5. Aaron says:

    I find that when dealing with persistent Value Objects, (usually via an Object Relational Mapper), there is no difference in the actual database structure for a persisted Value Object ie usually it WILL have a synthetic Primary Key.

    The difference tends to be in the way operations such as Delete can be cascaded from the parent Entity to the Value Object children without concern about any other entities holding a reference to the child.

    The Bounded Context of an Aggregate allows us (among other things) to apply similar cascading behaviour from Entity to Entity within the Aggregate.
    Sometimes (think enumerated values to fill drop down lists) we need to effectively elevate a Value Object to an Entity in the domain purely to define a finite set of values. In this case although they are not referenced by identity, they do act more like Entities, and may be referenced (ie shared) by many other Entities.

    Phew, explaining things really does clarify understanding :)

  6. agilejoe says:

    Aaron,

    Thanks for the comment but I would like to ask a clarifying question before I respond to a portion of your comment.

    “…we need to effectively elevate a Value Object to an Entity in the domain purely to define a finite set of values.”

    Your statement is in reference to values in a drop down box. I was wondering if you could expound upon this statement and give an example, Maybe not hear but in a post. I am curious to see in detail what you are referencing as I am having a hard time discerning how items in a drop down box are at one point Value Objects and later referenced as Entities.

    Regarding the repository layer reference, I agree completely that value objects for the most part with have some type of primary key in the persistence mechanism but it is important to understand that this key is only unique within the context of the repository layer and holds little value to the Domain Model, since the product owner does not care about this identity. The domain model should NOT enforce the constraints of the persistence mechanism if at all possible. I know easier said than done. But every effort must be made to keep foreign key, referential integrity semantics out of the actual domain model. Distillation is key from this perspective.

  7. Aaron says:

    Hi Joe,
    Yeah, elevating to an Entity possibly isn’t the best way to say it… I’ll see if I can think up an example and drop you a note…

  8. jmeridth says:

    This answers my question from above:

    “I agree completely that value objects for the most part with have some type of primary key in the persistence mechanism but it is important to understand that this key is only unique within the context of the repository layer and holds little value to the Domain Model, since the product owner does not care about this identity”

    Thank you Joe.

  9. Aaron says:

    Ok, this is probably a mistake – its past midnight and someone forced me to drink lager – so please excuse any total rubbish :)

    Expanding your example further:

    Lets say that in an authoritarian moment, you decided to restrict your Kid’s Attire. From now on, only TShirts of a permitted TShirtStyle can be worn.

    Coincidentally, your Kids have become rather obsessed with cataloguing their wardrobes, and have decided to use your new application to record all of their items of clothing. However due to your newly acquired mean streak, you intend to restrict any attempt to register Attire with an unpermitted TShirtStyle.

    To that end, you create a new object called TShirtStyle which consists of a Color and a StyleName – where StyleName could be something like V-Neck, Round-Neck or Collared.

    In terms of associations, we have:

    Kid -> ‘is permitted’ -> TShirtStyle
    Kid -> ‘has’ -> Attire
    Attire[ TShirt ]->TShirtStyle

    Now because you need to administer your application, you need to be able to Create and Delete TShirtStyles, and – in order to permit a Kid to wear a TShirt of Style x – you need to be able to Retrieve a list of TShirtStyles so that you can choose one to assign to a Kid.

    Now to me, TShirtStyle sounds like a Value Object – we’re never going to do: Repository.FindTShirtStyle(“White”, “V-Neck”) – we can just create a new one with those attributes. Specific Identity doesn’t matter to us, and any TShirtStyle’s with the same attribute values are equal.

    So while TShirtStyle is a ValueObject in the standard sense, we will need a Repository for it, and it acts in some ways like an Entity.

    Hope this makes some sense – it could well sound like nonsense by the time I wake up :)

  10. agilejoe says:

    Nice question Aaron. But for my sanity, I am going to follow up your comment in a post. I was going to answer it here but it was too long winded.

    Cheers.

  11. Aaron says:

    Hey Joe,
    Just a gentle nudge to see if you’ve had time to write up your thoughts on my previous comment. I’m interested to get your take on it. If you don’t want to post on it, feel free to email me (contact details on my site). Cheers

  12. Jorge says:

    Hi, im new to DDD, and i found it very interesting, but i’m a bit confused with entity and value objects. I found myself in a frecuent situation where i have objects that seems to be entity and value at the same time.For exapmle:
    I hava a University, that has a range of numbers to asigns to documents, so i model :

    Univ–>Range

    The fact is that each range must be unique for each Univ., and the Range must have the track of the following number to give. So for me this is an entity, but on the other hand, the range has no meaning without the university, so it is a value. Besides, the question ” who Univ this Range belong to?” don’t help me” because i could make the same question througth Univ.?

    Any idea of what my error is…
    Bye

  13. Ian Spence says:

    Joe, Looking forward to your next posting on DDD :-)

  14. Setya says:

    Joe,

    If you don’t mind, I need to see your thoughts on Aaron’s questions too. Feel free to email me to jsetya@gmail.com.

    Nice articles so far.

    Regards,

    Setya

  15. Jimmy Bogard says:

    Jorge,

    Remember, the primary difference to me between Entities and Value Objects is identity. If I have two instances to Value Objects with same internal values, they should be considered equal. That’s one of the reasons I created a generic Value Object base type:

    http://grabbagoft.blogspot.com/2007/06/generic-value-object-equality.html

    If you can’t make a Value Object

    - Immutable
    - Exhibit value equality rather than reference equality

    Then it probably isn’t a Value Object.

    Aaron,

    Just because you need to persist different kinds of TShirtStyles, doesn’t mean they’re not Value Objects. You’re combining two concepts:

    - Persistence
    - Behavior

    If you need to form a many-to-many relationship between an Entity and a Value Object, you can still do it. Just make sure your persistence layer (SQL Server, whatever) enforces the value object identity constraints (i.e., make the TShirtStyle part a unique constraint, so I can’t have two TShirtStyles have the same value).

    Hope this makes sense.

  16. Colin Jack says:

    Good post.

    I agree about the persistent ID that you often get for a VALUE OBJECT when persisting them to the database can be confusing but as you say this is a persistence concern and in reality does not detract from the idea.

  17. Joe Ocampo says:

    Glad this post added some value.

  18. lost mouse says:

    can you talk about aggregate?
    i like you article

  19. ronny stalker says:

    Hi thanks for this discussion. The whole value objects versus entities keeps on hurting my brain.

    I’m still finding it hard to think of a value object’s id (for persistance) not pervading into the model.

    For example i just can’t get my head around the fact that in the model we can use a value object but not give it some kind of identity like a name. If value objects do not have names/id – how can we tell them apart?

    I just look at my model and it seems like nothing will ever be a vlaue object apart from primitives cos i will always want to manage them.

    E.g a customer has a ‘country location, say, East Germany’. Then one day that country becomes ‘Germany’ – i am going to want to be able to change it.

    I just cannot seem to think of value objects without some kind of name…aargh my head hurts.

  20. ronny stalker says:

    Regarding my last comment. OK – I’m back a few days later and a little bit wiser.

    My brain does not hurt so much now.

    I feel like i understand Value objects a bit better since I read the DDD book’s ‘example on mixing paint’ (page 258, by Eric Evans)
    http://books.google.com/books?id=7dlaMs0SECsC&printsec=frontcover&dq=domain+driven+design#PPA253,M1

    Funnily enough, i find it difficult to answer my previous question despite my new found knowledge. The only advice i can give, is: “When struggling with value objects, just try to forget about the intricacies of the ‘relational DB storage issues’ and keep thinking in term of the domain.”

    I can, now, see that, when i wrote the comment, i was trying to ‘scale an over-hang’ (in terms of the steep learning curve that is ‘domain driven design’).

    Now that i have climbed a bit higher – the learning curve has flattened out onto a plateau. I am looking down and can’t even see the overhang that i was struggling with. However, i can say that it is better climb up a different route rather than attempting to tackle that particular obstacle.

    Other tips: Also, its a good idea to use steel crampons instead of aluminium. And wear a woolly hat…. and bring a flask of hot coco…erm ok… nuff said.

    .

  21. tonyweisb says:

    increase emission relatively external climatic news

  22. traviongib says:

    stabilized sources community possible

  23. hrychleahk says:

    response economics 100 program

  24. bakernadea says:

    occurred specific disease lapse agree email end net

  25. upwoodbart says:

    percent past scale stories

  26. wadleykemp says:

    primary shut production sun windows pollution

  27. ernieperso says:

    country intensity contends states estimate emit made north

  28. wadakamin says:

    scientific offset protocol seen sres anthropogenic

  29. lucillegin says:

    globe positive news worldwide controls

  30. holdinkueh says:

    forward main america inc troposphere partners

  31. danrellewe says:

    induce next reports reliable relatively conclude sensitivity

  32. stocwiella says:

    browser decrease times due observational led observed techniques

  33. clarrisaca says:

    circulation offset users continues link environment newsletter america

  34. delishawes says:

    scenarios developers 2009 forward

  35. anonymous says:

    The images are missing on this page?