Friday, April 22, 2011

Entities vs. Value Objects

As I mentioned in a previous post,  our application would consist of multiple layers, one of which is the model layer – services, factories, entities and repositories (*cough* session? *cough*).

But what do we mean when we say entity? or more precisely, how do we identify our entities, and what’s the best way to manage them and express the rest of the data? Let’s start be defining entities and value objects:

Entities

An Entity is an object that’s defined uniquely by an identity, we’ll usually persist those objects and they’ll contain both data and behaviors. They are the core of our domain, and require careful and well-thought out design – what one application may refer to as a User is probably not what another system will. Entities will probably contain references to other entities and value objects, but more on that when we talk about aggregates.

As a best practice, entities should focus on their domain’s business logic and be ignorant to their infrastructural concerns, such as database persistence. That’s where OR/M frameworks come in handy, helping us keep our entity a POCO (or POJO in the Java world), unlike other approaches such as Active Records which delegates the entity with the persistence responsibility.

Value Objects

On the other hand, Value Objects are not being tracked and are not uniquely identified. The most common example is the address object – It has a few properties that together represents a conceptual whole but it has no identity. Keep in mind that your domain may use addresses as entities if they need to be tracked uniquely – a billing address of a customer is probably a value object while in the real-estate domain it could be a uniquely identified estate. Value objects van contain references to other entities and value objects, though probably not as frequently as entities.

As a best practice, value objects should be immutable and cheap to create. Immutable objects are by definition objects that don’t change their value after creation, such as String or DateTime. For more on that, go here.

Often, value objects will contain either data only (also referred to as a Data Transfer Object, DTO) or behavior only.

Summary

Entities are objects that have an identity by which they can be tracked, they are the core of our domain and should be designed as precisely as possible with help from our domain expert. Value objects are objects that help us express a conceptual whole in a reusable way, they should be cheap to create and immutable.

No comments:

Post a Comment