In the SE classes at university we were taught OOAD and DDD (using Java) and encouraged to use it in our projects. Unfortunately a lot of challenges caused by the mutability of entities were not discussed:
- Unsuitability for multithreaded applications
- That it breaks data structures that rely on equals(), hashCode() or compareTo() (*)
- That it makes it hard to reason about the state of entities
These problems make it very hard for me to use DDD although I like the ideas behind it and a lot of libraries and frameworks (like ORM, serialization libraries -- basically everything that uses Java Beans) rely on the mutability of entities. The result is that I'm full of doubts when making architectural decisions and never happy with the outcome, no matter what I do. Either I get some Frankenstein's monster app where I have the entities immutable, but a lot of mutable glue to make it work (Builder, mutable DAO/DTO), or I have a fully mutable app full of WTFs (like sorting a list every time I use it instead of using a sorted data structure because an entity might have been changed since it was added to the list).
How do you deal with these problems? What's the way to go? Are there alternatives to DDD that don't require mutability?
I would personally prefer to go fully immutable, but that would make it very hard or even impossible to use some libraries that require Java Beans. Of course I could switch to functional programming but I'm not sure wheather it's a good replacement for the typical projects where DDD is used.
(*) Well, only if you override them. But where's the point in using a set if you don't?