Alex Rivera | Logout

Value objects in DDD - Why immutable?

Asked 2011-01-03T01:55:10.093
47

I don't get why value objects in DDD should be immutable, nor do I see how this is easily done. (I'm focusing on C# and Entity Framework, if that matters.)

For example, let's consider the classic Address value object. If you needed to change "123 Main St" to "123 Main Street", why should I need to construct a whole new object instead of saying myCustomer.Address.AddressLine1 = "123 Main Street"? (Even if Entity Framework supported structs, this would still be a problem, wouldn't it?)

I understand (I think) the idea that value objects don't have an identity and are part of a domain object, but can someone explain why immutability is a Good Thing?


EDIT: My final question here really should be "Can someone explain why immutability is a Good Thing as applied to Value Objects?" Sorry for the confusion!


EDIT: To clairfy, I am not asking about CLR value types (vs reference types). I'm asking about the higher level DDD concept of Value Objects.

For example, here is a hack-ish way to implement immutable value types for Entity Framework: http://rogeralsing.com/2009/05/21/entity-framework-4-immutable-value-objects. Basically, he just makes all setters private. Why go through the trouble of doing this?

Edit
Report

1 Answer

5

This might not be the complete answer. I am only answering your question on the advantages of Immutability.

  1. Because Immutable objects are thread safe. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
  2. The references to the immutable objects can be easily shared or cached without having to copy or clone them as their state can not be changed ever after construction.
  3. For more advantages of Immutability you look here (LBushkin's answer) What's the advantage of a String being Immutable?

This is an example by Martin Fowler on why value objects should be Immutable.

Alright, while it is not mandatory to make VO as immutable (even DDD book doesn't say they have to be immutable), the main idea, in DDD, to make it a VO seems to be not to deal with life cycle complexities like that of an Entity. Look here for more details.

answered 2011-01-03T02:04:43.523

Your Answer