in

 

Jimmy Bogard

Assistant to the assistant to the regional manager

Entities, Value Objects, Aggregates and Roots

Taking a small detour before I deliver the first installment in the Domain-Driven Design: Supple Design Patterns series, I'd like to cover the basic elements of Domain-Driven Design modeling:

  • Entities
  • Value Objects
  • Aggregates and Roots

I'd like to cover these aspects partially because these ideas play a large role in the later ideas, but also because Rob asked me to (see comments).  If you'd like an in-depth discussion of these topics, just check out Eric Evans' Domain-Driven Design, chapters 5 and 6.

Entities

From Evans:

Many objects are not fundamentally defined by their attributes, but rather by a thread of continuity and identity.

In traditional object-oriented design, you might start modeling by identifying nouns and verbs.  In DDD modeling, I try to key in on terms coming out of our Ubiquitous Language that exhibit a thread of identity.

For example, consider a Person concept.  If I have two Person objects, with the same Name, are they same Person?  Bob Smith from Cheyenne, Wyoming and Bob Smith from Tallahassee, Florida might not agree.  A popular gimmick I've seen is interviewing a Person with a famous name (but different identity).  So if Name isn't a Person's distinguishing attribute, what is?  Address?  Social Security Number?  Not for non-US citizens, what about a Kiwi Bob Smith?

In each of these examples, a Person is identified by more than their attributes, such as Name, Address, PhoneNumber, etc.  A Person has a unique identity that manifests itself if different ways in different systems.  Each system has their own attributes they're concerned with, but the Person is always the same entity (not class, that's different).

My "litmus test" for Entities is a simple question:

If two instances of the same object have different attribute values, but same identity value, are they the same entity?

If the answer is "yes", and I care about an identity, then the class is indeed an entity.  I model entities with reference objects (classes), and I give them a surrogate identity (i.e., probably a GUID).  Additionally, my model must include what it means to have the same identity.  That means overriding Equals, looking solely at the identity and not attributes.

Value Objects

From Evans:

Many objects have no conceptual identity.  These objects describe characteristics of a thing.

When I don't care about some object's identity, I carefully consider making the concept a value object.  For example, if I have a system that models Paint buckets, the Color is a great candidate for a Value Object.  I care about one specific PaintBucket or another, as I paint with individual PaintBuckets that will eventually be drained of their paint.

But when checking the Color of a specific PaintBucket, the Color has no identity in an of itself.  If I have two Colors with the exact same pigmentation values, I consider them to be the same.

When designing Value Objects, I want to keep them away from the trappings of Entity life cycles, so I make the Value Object immutable, and remove any concept of identity.  Additionally, I'll override Equals to compare attributes, so that attribute equality is represented in my model.

By making my Value Object immutable, many operations are greatly simplified, as I'm immediately led down paths to Side-Effect Free Functions.  I don't create a type with a bunch of read-write properties and call it a Value Object.  I make it immutable, put all of the attributes in the constructor, and enforce attribute equality.

Value Objects, like any other pattern, can be over-applied if you go hunting for opportunities.  Value Objects should represent concepts in your Ubiquitous Language, and a domain expert should be able to recognize it in your model.

Aggregates and Roots

In real life, many concepts have relationships to each other.  I have a set of credit cards, and each credit card has an owner (me).  Each credit card has a billing institution, and each banking institution has a set of credit accounts, each of which may or may not be a credit card.  If I were to represent all of these concepts as classes, what would the relationships be?

Should I represent every conceivable relationship possible in my object model?  Where do I draw the line between whether or not to create a reference?  If I have a reference between two entities, how should I handle persistence?  Do updates cascade?  Suppose an Employer has reference to their Manager directly.  If I change the Employee.Manager.Name, and save the Employee, does the Manager's Name get changed?

Object modeling is complex as it is.  Invariants need to be enforced not only in an Entity, but in all the Entities that are referenced as well.  That gets tough to maintain, and quick!

Aggregates draw a boundary around one or more Entities.  An Aggregate enforces invariants for all its Entities for any operation it supports.  Each Aggregate has a Root Entity, which is the only member of the Aggregate that any object outside the Aggregate is allowed to hold a reference to.  From Evans, the rules we need to enforce include:

  • The root Entity has global identity and is ultimately responsible for checking invariants
  • Root Entities have global identity.  Entities inside the boundary have local identity, unique only within the Aggregate.
  • Nothing outside the Aggregate boundary can hold a reference to anything inside, except to the root Entity.  The root Entity can hand references to the internal Entities to other objects, but they can only use them transiently (within a single method or block).
  • Only Aggregate Roots can be obtained directly with database queries.  Everything else must be done through traversal.
  • Objects within the Aggregate can hold references to other Aggregate roots.
  • A delete operation must remove everything within the Aggregate boundary all at once
  • When a change to any object within the Aggregate boundary is committed, all invariants of the whole Aggregate must be satisfied.

That's a lot of rules!  All of them just come from the idea of creating a boundary around our Aggregates.  The boundary simplifies our model, as it forces us to consider each relationship very carefully, and within a well-defined set of rules.  Maintaining bi-directional associations is difficult enough without persistence thrown into the mix, so by modeling our relationships around real-world use cases, we can greatly simplify our model.

Not all relationships need to be represented through associations.  In the Employee/Manager relationship, I can have a Manager directly off the Employee, but to get a Manager's DirectReports, I'll ask the EmployeeRepository.  Since Employee is an Aggregate Root, it's fine to have an Employee reference its Manager.

Modeling and simplification

One of my favorite quotes from Evans' book is:

Translation blunts communication and makes knowledge crunching anemic.

To avoid translation, we'll represent real-world concepts in our conceptual model, and our conceptual model expressed as code through Entities and Value Objects (and Services).  To simplify our model, we'll use Aggregates and Roots, enforcing invariants at each operation.  In all cases, I should be able to represent our conceptual model in our code, and it should make sense to our domain expert, as they'll see the Ubiquitous Language represented.

When the conceptual model we create with the domain expert is realized effectively in code, we'll find that not only to technical refactorings become easier, but enhancements to our model as well.  Entities and Value Objects are but a slice in the DDD world, but a core concept which many other ideas are built upon.

Comments

 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

May 21, 2008 12:40 AM
 

Mario A Chavez said:

Jimmy, would you mind if I translate this post to spanish and repost it in my blog with your credits?

May 21, 2008 1:12 AM
 

Entities, Value Objects, Aggregates and Roots said:

Pingback from  Entities, Value Objects, Aggregates and Roots

May 21, 2008 2:14 AM
 

Fredrik said:

Awesome post; a great summary of the concepts :)

Looking forward to the future posts on DDD.

May 21, 2008 6:56 AM
 

bogardj said:

@Mario

Go for it! I'd do it myself, pero yo hablo español solo muy poquito.

May 21, 2008 7:01 AM
 

Dew Drop - May 21, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - May 21, 2008 | Alvin Ashcraft's Morning Dew

May 21, 2008 8:12 AM
 

Ben Scheirman said:

Good stuff.  I prefer to ask myself the reverse of the identity question, which reads like:

If 2 objects have the same exact attributes, are they the same entity?

In the case of the 2 Bob Smith's, even if those are the only attributes you currently store, the concept of identity still holds.  ie:  There is a distinguishing set of attributes that is more exhaustive than our subset in the domain that can uniquely identify an entity.  If this fits, then you have an entity.  If not, then it's a value object.

Money, map routes, commands, etc are all good examples of value objects.  You wouldn't care which instance of the 5 dollars you had, you just care about the value.

May 21, 2008 2:13 PM
 

Andrey Shchekin said:

I do not understand one thing about aggregates. If I have an advanced O/R mapper that tracks changes to Employeee.Manager.DirectReports and lazy-loads it if required, do I really need to make such traversal forbidden?

May 22, 2008 1:21 AM
 

Reflective Perspective - Chris Alcock » The Morning Brew #99 said:

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #99

May 22, 2008 2:19 AM
 

bogardj said:

@Andrey

No, not necessarily.  No matter what, bidirectional associations are tough to manage, and you can't rely on your ORM to do it for you.

For example, suppose you do something like Employee.Manager.DirectReports.Remove(Employee).  Who is Employee.Manager now?  When does DirectReports get updated, automatically when I change the Manager?

I like to drive associations strictly through stories and scenarios, and allow some associations to be done through the Repository.  Something like EmployeeRepository.FindDirectReportsFor(Manager).  Eventually, you'll have to manage associations strictly through your Entities.

May 22, 2008 7:40 AM
 

foobar said:

Really?  You'd still require an instance of a manager to get its employees?  I certainly hope not.

May 23, 2008 5:19 PM
 

The Inquisitive Coder » Blog Archive » Weekly Links 5 said:

Pingback from  The Inquisitive Coder  » Blog Archive   » Weekly Links 5

May 24, 2008 2:31 AM
 

bogardj said:

@foobar

I assume you're talking about the difference between:

EmployeeRepository.FindDirectReportsFor(Manager)

and

EmployeeRepository.FindDirectReportsFor(ManagerId)

?

Design of this would definitely be driven by use cases and actual stories.  I would go with whatever made sense.  Hard to say one is always right or not, always "it depends"

May 24, 2008 9:17 AM
 

Kaushik said:

When using aggregates in real world, I sometimes come across cases where the root entity seems to differ based on the usecase i am looking at. Have you come across any such cases?

>>Nothing outside the Aggregate boundary can hold a reference to anything inside

I sometimes have seen need for some shared objects that do not logically belong to one root but rather to two. In such cases, it was more easier to let the shared object be referred by both roots.

I am writing a series of blogs on implementing DDD. I have detailed how to implement entities and vo's. Have a look at them at stochastyk.blogspot.com/.../series-on-domain-driven-design.html.

May 25, 2008 10:53 PM
 

bogardj said:

@Kaushik

I'd say that's pretty common.  I redraw the aggregate lines a few times before it settles into something stable.  I kept forgetting that child entities in an aggregate only have unique identity inside an aggregate.  Once I defined these entities with this in mind, it eliminates quite a few aggregate boundary candidates.

If you have one entity that seems to belong to two roots, it's likely you have three roots in actuality.

May 26, 2008 8:15 AM
 

Mario A Chavez said:

Jimmy, This post is in Spanish now, thanks for let me repost it. mario-chavez.blogspot.com/.../entidades-objetos-por-valor-agregados-y.html

May 26, 2008 12:13 PM
 

Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog said:

Pingback from  Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog

May 26, 2008 3:31 PM
 

Weekly Links: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog International said:

Pingback from  Weekly Links: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog International

May 26, 2008 3:32 PM
 

Jimmy Bogard said:

A question came up on the ALT.NET message board asking whether Value Objects should be used across service

August 12, 2008 8:05 AM
 

Jimmy Bogard said:

One of the confusing aspects of those new to DDD is the concept of a Repository. From Fowler's Patterns

August 19, 2008 10:31 PM
 

Lipitor prescription side effects. said:

Generic lipitor. Lipitor dosage morning or night. Lipitor the drug. Lipitor. Lipitor side effects.

August 21, 2008 3:39 PM
 

Andrei Butnaru's blog said:

Training module - Domain Driven Design 1

August 23, 2008 9:16 AM
 

Mark Holtman said:

Jimmy,

Thanks for a very concise explanation of these basic concepts. Your concrete examples helped solidify some of my thinking. I'm making my way through Evan's DDD book at the moment and was struggling with what a Value Object is, ideally.

August 28, 2008 9:38 AM
 

Pluggable Dependencies Intermission « Cav’s Weblog said:

Pingback from  Pluggable Dependencies Intermission « Cav’s Weblog

September 2, 2008 5:33 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About bogardj

I'm a senior consultant with Headspring Systems in Austin, TX. My focus is using .NET technologies together with Agile methodologies. Back in 2005, I drank the Agile punch and haven't looked at a waterfall the same since.
Copyright Los Techies 2007. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems