Value Objects holding Entities - domain-driven-design

In the book, Eric Evans shows an example where an VALUE OBJECT holds ENTITIES. VALUE OBJECTS are immutable, ENTITIES not.
The question is: If an ENTITY that
is referenced from an VALUE OBJECT change its state, was the immutability been broken?
In my opinion it doesn't break the immutability, because the "value" of the
object lies on the ENTITIES array, not on their states.
What do you guys think?

It depends if you can mutate the entities directly through the VO or not.
Imagine a VO instance that can be shared between multiple objects. If the VO contains a mutable entity and exposes it as a public member, multiple clients may update the entity concurrently. This leads to problems you would expect not to happen with actual immutability.
If the VO only holds the ID of the referenced entity on the other hand, you would have to fetch a brand new instance from a Repository before changing it, avoiding the shared mutable state issue.

Related

Is every property of an Entity in domain driven design a value object?

I'm reading "Patterns, Principles, and Practices of Domain-Driven Design". The book suggests that properties of an Entity should be value objects in order to model domain's ubiquities language. I've seen many examples like EmailAddress or Age with only one field to model domain concepts. I'm confused about it. Is every property of an Entity a value object? Can you provide examples when we can use normal languages provided data types for properties?
No, not every property of an entity is a value object.
Properties of entities are one of the following:
As you already know, value objects. Value objects represent simple values without identity.
Primitives. These are just value objects from a DDD perspective, really. Primitives are ok to use in DDD, but take care not to become a victim of Primitive Obsession.
Entities. An entity can contain other entities. All entities that have direct (navigable) references between them are part of the same Aggregate. The "top-most" entity within an aggregate is called the Aggregate Root. Only the root has a global identity, inner entities have only local identity.
References to entities of other aggregates. Never reference these directly, use an ID. IDs themselves can in turn be modeled as value objects.
I think that your real question is: Is every value object a Class?
Because you can think that for the Age a Java Integer can be enough and this is true. So you have in your entity Person a value object Age of type Integer, there is no need of an age type.
OOP also says that an object is state + behaviour. In your Age case, I assume that it has no behavior so a simple primitive or wrapper class will do the trick, in fact I would go with option this because is simpler.
My advise is, go with a primitive/wrapper class and if you advert that some behavior is needed in that value object, make a class/type.

Domain Driven Design; Can ValueObject contains invariants or specifications?

I'm starting to play with Domain Driven Design and have a question about ValueObjects :
Can they contains invariants or other specifications ?
Consider an immutable ValueObject :
ValueObject (
prop integer: Int
prop string: String
// Value and copy constructor
// Observers for integer and string
// Equality methods on integer and string value
)
Can I add some invariants such that integer > 0 & < 42. Or do they have to be simple transfer without any logic ?
I hope they can but need a confirmation.
A value object (VO) encapsulates a value and its business requirements . This is its purpose: to model a business concept (with its constraints) which happens to be a simple (not always single) value.
A VO is not a Data transfer object (DTO) precisely because it defines a business concept that is valid only in the containing bounded context, while a DTO is meant to cross boundaries.
Value objects should handle the invariants for the data that they encapsulate, or at least as much of it as they can. I tend to do the following, which is actually similar to entities except for the immutable bit:
Constructors should make sure it is created in a valid state
The VO's state is encapsulated, and all changes to it are done through controlled methods/etc
Because value objects are immutable, method changes return a new value object rather than updating the existing state
Having the value objects own their own business logic really helps clean up the code in the entities that use these value objects. This can become a problem with big aggregates\entities, so look for opportunities to pull this behavior out into value objects.
It also makes unit testing lots of edge cases MUCH easier, as you are testing the value object on its own.
Your entity may need to do validation across multiple value objects before decides a change CAN happen, but then the value object is responsible for the change itself.

Repositories and Roots of aggregates

I'm reading a book by Eric Evans DDD.
And I found a contradiction.
Chapter books about aggregates:
Choose one ENTITY to be the root of each AGGREGATE, and control all
access to the objects inside the boundary through the root.
Chapter books about repositories:
A subset of persistent objects must be globally accessible through a
search based on object attributes. Such access is needed for the roots
of AGGREGATES that are not convenient to reach by traversal. They are
usually ENTITIES, sometimes VALUE OBJECTS with complex internal
structure, and sometimes enumerated VALUES. Providing access to other
objects muddies important distinctions.
Provide REPOSITORIES only for AGGREGATE roots that actually need
direct access.
It can be concluded that the root of the aggregate can be:
entity
value object
enumerated values
Correctly I understood everything?
Or may be right:
Provide REPOSITORIES only for
aggregate roots
value objects
enumerated values
?
And what is enumerated values(which needs its own repository!)?
Per #Marco's comment above, the root of an aggregate can only be an entity (i.e. something with an ID property). An example of this would be an Order object. No matter how many attributes you change on an Order its quality is determined by its Id property and nothing else.
A value object (often implemented as a struct in many languages) does not have an ID. A common example of this would be a Money value object with a Dollars property and Cents property. Because it has no ID, the concept of querying it by ID does not apply, and thus the concept of a repository does not apply. An aggregate could have a value object as a property, though (e.g. the Total property on an Order aggregate).
An enumerated type is just a list of name/value pairs. It uses the enum keyword in several languages. Again, there's no ID for the enum nor any of its members, so the concept of a repository does not apply. The concept of an enum is useful in DDD because it helps express the domain model better than, say, magic numbers e.g. order.Status = OrderStatus.Submitted vs order.Status = 1.

Persisting references non-root entities outside of aggregate

All material on DDD specify this as a strict no no, but i recently came across a scenario that makes a compelling case for thinking otherwise. Imagine 2 aggregate roots Template and Document where Template --> (1:n) TemplateParam, Document --> (1:n) ParamValue and finally the 2 roots have a reference Document --> (n:1) Template.
Given aggregate root constraint ParamValue should not persist a reference to TemplateParam, only it can refer it through a transient reference obtained through Template aggregate root. Now if i want to have a rule enforce like "each ParamValue of document should refer to a valid TemplateParam belonging to the Template referred to by its owning document". Ideally at db level i would let ParamValue have FK to the TemplateValue, how to do it in DDD paradigm ??
Aggregate Roots are there for a reason. They act as a single entry point to a group of related entities in order to enforce their invariants. They make sure that no external object can mess up with these entities and potentially violate their invariants.
However, in your particular scenario, even if ParamValue holds a direct reference to TemplateParam, TemplateParam is not at risk of being modified by an entity in the Document aggregate. The value associated to a parameter for a given document will be modified, but not the parameter per say.
To make sure this is the case, you can make TemplateParam an immutable value object :
(in C#)
public class TemplateParam
{
private readonly string name;
public TemplateParam(string name)
{
this.name = name;
}
public string Name
{
get { return name; }
}
}
Thus you can encapsulate TemplateParam in ParamValue with no risk that one of the Template aggregate's invariants will be broken due to the "externalization" of TemplateParam.
Technically speaking that may be a violation of DDD's aggregate root constraint, but I don't believe it is one in spirit as long as you keep the "externalized" entity immutable and don't modify the object graph it originally belongs to.
One way you could go about this is to have the Template entity have a factory method for creating Document instances, which can enforce the constraint that all ParamValue instances are associated with appropriate TemplateParam. If the document is immutable then you're done. Otherwise, you can apply updates to the document through its associated template. This template can be referenced directly from the document or with an ID in which case the encapsulating application service would retrieve it when required for an operation. Direct references between ARs are not a strict violation of DDD, in fact the blue book specifies that are the only things that can be referenced by external ARs. It has become a constraint as of late because of other considerations such as consistency, performance, ORM mapping, etc. Take a look at this series of articles on effective aggregate design for some inspiration.

Value vs Entity objects (Domain Driven Design)

I have just started reading DDD. I am unable to completely grasp the concept of Entity vs Value objects.. Can someone please explain the problems (maintainability, performance.. etc) a system could face when a Value object is designed as a Entity object? Example would be great...
Reduced to the essential distinction, identity matters for entities, but does not matter for value objects. For example, someone's Name is a value object. A Customer entity might be composed of a customer Name (value object), List<Order> OrderHistory (List of entities), and perhaps a default Address (typically a value object). The Customer Entity would have an ID, and each order would have an ID, but a Name should not; generally, within the object model anyway, the identity of an Address probably does not matter.
Value objects can typically be represented as immutable objects; changing one property of a value object essentially destroys the old object and creates a new one, because you're not as concerned with identity as with content. Properly, the Equals instance method on Name would return "true" as long as the object's properties are identical to the properties of another instance.
However, changing some attribute of an entity like Customer doesn't destroy the customer; a Customer entity is typically mutable. The identity remains the same (at least once the object has been persisted).
You probably create value objects without realizing it; anytime you are representing some aspect of an Entity by creating a fine-grained class, you've got a value object. For example, a class IPAddress, which has some constraints on valid values but is composed of simpler datatypes, would be a value object. An EmailAddress could be a string, or it could be a value object with its own set of behaviors.
It's quite possible that even items that have an identity in your database don't have an identity in your object model. But the simplest case is a composite of some attributes that make sense together. You probably don't want to have Customer.FirstName, Customer.LastName, Customer.MiddleInitial and Customer.Title when you can compose those together as Customer.Name; they'll probably be multiple fields in your database by the time you think about persistence, but your object model doesn't care.
Any object that is collectively defined by all of it attributes is a value object. If any of the attributes change you have a new instance of a value object. This is why value objects are defined as immutable.
If the object is not fully defined by all of its attributes then there are a subset of attributes that make up the identity of the object. The remaining attributes can change without redefining the object. This kind of object cannot be defined at immutable.
A simpler way of making the distinction is to think of value objects as static data that will never change and entities as data that evolves in your application.
Value Types :
Value types do not exist on his own, depends on Entity types.
Value Type object belongs to an Entity Type Object.
The lifespan of a value type instance is bounded by the lifespan of the owning entity instance.
Three Value types: Basic(primitive datatypes), Composite(Address) and Collection(Map, List, Arrays)
Entities:
Entity types can exist on his own (Identity)
An entity has its own life-cycle. It may exist independently of any other entity.
For example: Person, Organisation, College, Mobile, Home etc.. every object has its own identity
I don't know if the following is correct, but I would say that in the case of an Address object, we want to use it as a Value Object instead of an Entity because changes to the entity would be reflected on all linked objects (a Person for instance).
Take this case: You are living in your house with some other people. If we would use Entity for Address, I would argue that there would be one unique Address that all Person objects link to. If one person moves out, you want to update his address. If you would update the properties of the Address Entity, all people would have a different address. In the case of a Value Object, we would not be able to edit the Address (since it is immutable) and we would be forced to provide a new Address for that Person.
Does this sound right? I must say that I was/am also still confused about this difference, after reading the DDD book.
Going one step further, how would this be modelled in the database? Would you have all properties of the Address object as columns in the Person table or would you create a separate Address table that would also have a unique identifier? In the latter case, the people living in the same house would each have a different instance of an Address object, but those objects would be the same except for their ID property.
address can be entity or value object that depends on the busiess process. address object can be entity in courier service application but address can be value object in some other application. in courier application identity matters for address object
3 distinction between Entities and Value Objects
Identifier vs structural equality:
Entities have identifier,entities are the same if they have the same
identifier.
Value Objects on beyond the hand have structural equality, we consider two
value objects equal when all the fields are the same. Value objects cannot
have identifier.
Mutability vs immutability:
Value Objects are immutable data structures whereas entities change during
their life time.
Lifespan: Value Objects Should belong to Entities
In a very simple sentence I can say, we have three types of equality:
Identifier equality: a class has id filed and two objects are compared with their id field value.
Reference equality: if a reference to two objects has a same address in memory.
Structural equality: two objects are equal if all members of them are matched.
Identifier equality refers only to Entity and structural equality refers to Value Object only. In fact Value Objects do not have id and we can use them interchangeably. also value objects must be immutable and entities can be mutable and value objects will not have nay table in database.
I asked about this in another thread and I think I'm still confused. I may be confusing performance considerations with data modelling. In our Cataloging application, a Customer doesn't change until it needs to. That sounds dumb - but the 'reads' of customer data far outnumber the 'writes' and since many many web requests are all hitting on the 'active set' of objects, I don't want to keep loading Customers time and again. So I was headed down an immutable road for the Customer object - load it, cache it, and serve up the same one to the 99% of (multi-threaded) requests that want to see the Customer. Then, when a customer changes something, get an 'editor' to make a new Customer and invalidate the old one.
My concern is if many threads see the same customer object and it is mutable, then when one thread starts to change it mayhem ensues in the others.
My problems now are, 1) is this reasonable, and 2) how best to do this without duplicating a lot of code about the properties.
Consider the following examples from Wikipedia, in order to better understand the difference between Value Objects and Entities:
Value Object: When people exchange dollar bills, they generally do not
distinguish between each unique bill; they only are concerned about the face
value of the dollar bill. In this context, dollar bills are Value Objects. However,
the Federal Reserve may be concerned about each unique bill; in this context each
bill would be an entity.
Entity: Most airlines distinguish each seat uniquely on every flight. Each seat is
an entity in this context. However, Southwest Airlines, EasyJet and Ryanair do
not distinguish between every seat; all seats are the same. In this context, a seat is
actually a Value Object.

Resources