Home » Code » What is the difference between Entities and Value Objects?

What is the difference between Entities and Value Objects?

Posted by on April 30th, 2014

What is the difference between Entities and Value Objects
As you begin to delve deeper and deeper into the world of computer programming you start to uncover lots and lots of new theories and concepts.

One such idea that isn’t intuitively obvious is Value Objects. A Value Object is an important concept in Domain Driven Design (DDD).

For this article you don’t have to worry about Domain Driven Design or any of the related concepts as I’m going to be purely focusing on Value Objects. However, hopefully this is the first step towards a better understand of Domain Driven Design in general.

Note: I’m assuming you have a good understanding of Object Oriented Programming. If not, you will probably want to read up on that before reading this article.

Entities verses Value Objects

In Object Oriented Programming, we represent related attributes and methods as an Object.

So for example, a Person could be an Object within our application. A person will have a name, email address and password as well as many other attributes. Within our database this person is represented by an id. This means that the person could change their name, email and password but it would still be the same person. When an object can change it’s attributes but remain the same object we call it an Entity. An Entity is mutable because it can change it’s attributes without changing the identity of the object. The Entity object will maintain the identity because it has an id in the database.

Imagine that our application allows the person to track their current location. When the person is able to successfully connect to the internet and authenticate with our application a new Location object is created. This Location object has attributes for longitude and latitude. The Location object is a Value Object because we don’t care about the specific instance of the object we only care that it is a location.

When the person changes location, we don’t have to update the Location object, we can simply create a new Location object. The Location object never changes it’s attributes from the moment it is created until the moment it is destroyed. When an object’s attributes cannot be changed, it is known as immutable.

Another important distinction is, Value Objects equality is not based upon identity. So for example, when you create two Location objects with the same longitude and latitude attributes those two objects will be equal to one another. The Person object on the other hand does base equality on identity because it is a single representation with an id. If you had two people with the exact same name, they would not be the same person.

How to identify Value Objects?

So hopefully you can see that we can generally make the distinction between an Entity and a Value Object when an object is represented with an id.

An Entity’s attributes can change, but it remains the same representation within our system because of it’s unique identifier. Whereas a Value Object is a single instance of an object that is created and then destroyed. We don’t care about a specific instance of a Value Object and we can’t change it’s attributes.

So how do you know when to use an Entity and when to use a Value Object? Well the decision really comes down to the context of the application.

Imagine that in the example from earlier, our application is not just a generic social application, it is actually Foursquare. Now every individual Location object does have a unique identifier because many different users can checkin to that location over time. Now the Location object is an Entity, not a Value Object.

On the other hand, imagine that we are the owner of a power plant that records activity around it’s security fence. The security fence has many locations where activity is recorded for monitoring purposes. Each location around the fence is an Entity because we care about recording activity at those specific locations. Whenever a suspicious person walks past one of our locations an incident is recorded in the database. In this example, a person is a Value Object because we don’t care about any particular person, we only care that a person triggered one of the security locations.

So whether an object is an Entity or a Value Object really depends on the context of how you are using it within your application. Generally speaking objects like location, dates, numbers or money will nearly always be Value Objects, and objects like people, products, files or sales will nearly always be entities.

Why is the distinction between Value Objects and Entity Objects important?

You are probably thinking, “why is the distinction between Value Objects and Entity Objects important?”.

Well it’s actually really quite important for a number of reasons.

Firstly, when you have two Entities with the same attributes, these two objects are not the same because they have two different identities. However, when you have two Value Objects with the same values, these two objects do have equality and can therefore can be interchanged freely. When you can substitute one object for another, the object is a Value object (in other words, the value is in the object, rather than the identity of the object). You couldn’t interchange Entities because there would be unwanted side effects.

Secondly, overtime an Entity’s properties will change, but it will remain the same Entity. For example, if a user changes their email address. However when your application needs to change a Value Object property, the whole object needs to be destroyed and a new one should replace it. For example, when you make a payment, the money object isn’t given back to you as change, you are given a new money object of a lower value.

Conclusion

The difference between Entities and Value objects is an important concept in Domain Driven Design. In DDD, it’s important to identify the difference between Entities and Value Objects in order to model the real world correctly in our application.

As I mentioned in this post, it’s important to fully understand the context of what you are building so that you know when an object should be an Entity and when it should be a Value Object. Just because at first glance and object would seem to have an identity, does not mean that it should be an Entity. Modelling a concept as an Entity with an identity, when it should be an immutable Value Object can have unwanted side effects.

Immutable Value Objects are an important part of building an application that correctly represents the intended design. Using Value Objects for things such as money for example, also ensures that mistakes aren’t made due to an object’s changing state through time.

Understanding the difference between Entities and Value Objects isn’t always apparent, and will require that you fully get your head around the context of the application you are building. However, the distinction is important, and is something that you should be aware of as you model a real world system as a new application in code.

Philip Brown

Hey, I'm Philip Brown, a designer and developer from Durham, England. I create websites and web based applications from the ground up. In 2011 I founded a company called Yellow Flag. If you want to find out more about me, you can follow me on Twitter or Google Plus.

  • nticaric

    Nice article!

  • cheeker

    I would like to ask how to use DDD with ORM e.g. eloquent because tendency is to make eloquent model and put methods to manipulate this data inside it. Repository pattern should be implmented to hide eloquent ORM details but how to do it without number of method explosion? Thanks very much for reply and good articles.

    • philpalmieri

      hi cheeker

      there are apples/oranges.. your ORM ‘should not’ – i say those words lightly.. be your direct mapping of your model.. they should be injected into your ‘model’.. So your location / person would not be an ORM / Eloquent model, it is its own thing that is injected with an eloquent instance to populate itself

      • cheeker

        Se there should be Entity e.g. person, that is plain class, which will receive in constructor instance of eloquent ORM mode personEloquent or better personRepository which will use Eloquent person model, right?

        • Yeah, Active Record style ORMs like Eloquent aren’t true to the nature of DDD. You should look at Doctrine which uses the DataMapper pattern.

          • cheeker

            Is there a neat way how to use Active record ORM e.g. Eloquent “correctly” without heavy bending in DDD? OR is it contraproductive?

          • The way you would normally use Eloquent is how you use the Active Record pattern http://en.wikipedia.org/wiki/Active_record_pattern

            To follow the DDD way, you could return a standard object from a repository, yeah.

  • santacruz

    Great writeup!

  • This is a very nice explanation. Clear and quite short. Its actually very helpfull, especially where you explain that deciding wether something is an entity or value object depends on the context.

    Thank you a lot

  • alireza Rahmani khalili

    very nice! I like it

  • Pingback: 6 Principles for Writing Maintainable Code | Culttt()

  • Pingback: Creating a PHP Shopping Basket Part 1 - Money, Currency and Taxes | Culttt()

  • codeatbusiness

    Hi Philip, one question. I’m working with Eloquent and I have three Tables: Customer, Partner and Contact. Then I have a fourth table with a polymorphic relationship called Addresses. I read before about the Address as Value Objects and I’m not persisting those Addresses using any Address identifier, only I related with each Customer, Partner or Contact model.

    What is the way you recommend me for persisting those Addresses? Do I need use Value Objects and, is correct to use a separated table, or is better to use the Root Entity for the Address persistance than this way?

    This is the structure of the Tables:

    Customer (id, customer_name, …)
    Partner (id, partner_name, …)
    Contact (id, contact_name, …)

    Addresses (line1, line2, city, zipcode, state, country, addressable_id, addresable_type)

    Thanks in advanced.

    • The decision as to whether the Address should be a Value Object really depends on the context of your application.

      If the Address was a Value Object you would store it as part of the record, usually as a serialised object. I don’t think Eloquent has a better way to do it.

      But to be honest it sounds like the Address is not a Value Object in your case. Just because an Address is a Value Object in certain applications, doesn’t mean it will be for all applications.

      • codeatbusiness

        Great answer as always. I suppose that would be better candidates for Value Objects some of the Address parts (zipcode, country, state, …) Many thanks Philip! Have a great day!

  • Ricardo Saul

    Great article!