EntitiesWhen two objects are deemed equal on the basis of their identity, they are considered "Entities". Suppose, you have two Employee objects in your system i.e. employee1 and employee2. The only way your code determines that the two objects are equal is by comparing the employee ids of the two objects. If the two ids match, these objects are considered equal.
Entity objects are mutable. We should be able to change specific properties of the entity object and be able to save it.
In terms of database storage, an entity should be stored in its own table.
Value ObjectsValue Objects have no conceptual identity. When two objects are deemed equal only if all their members match, they are considered "Value Objects". For example, you have two addresses i.e. address1 and address2. In order to determine whether the two addresses are equal, we will have to compare all the fields inside the address object i.e. Street Name, City, State, Country, etc. If all the fields match then only they are considered equal otherwise not.
Value Objects should be immutable. If we need to change some part of it, we should be creating a new instance of value object instead of updating the existing one.
For database storage, the value object data should be stored with the entity object itself instead of storing in a separate table. For example, for employee address, it's preferable to store the address fields in the employee table itself rather than a separate Address table.
Context DependencyThe same thing can be a value object in one application and and entity in another. For example, the dollar bill might be a value object in a casino application, however, it might be an entity in federal bank application. The bank might want to keep each bill based on it's identity, according to their application needs.
ConclusionUsing Value objects can simplify the design in instances where we can reuse the same object instead of creating multiple copies of the same thing. This might be more efficient in terms of memory as only one object might be used instead of creating multiple copies of the same value object again and again. Making it immutable might be extra work initially but it helps in communicating the design decisions more clearly to future code readers.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)