Immutable objects are great because they require no special care or feeding in multi-threaded applications. However many objects fall just short of being naturally immutable. For example, an order which is submitted, processed, and is assigned a permanent ID once the order is filled. The ID cannot be given at the time the order is created and submitted, but arrives later (or perhaps never).
Possible solutions:
- Assign an additional unique ID at the time of order creation. Then, when the permanent (order filled) ID comes, store it in a Map. So the order class would be immutable. Then, if the Map key did not exist, we'd know the order was not filled yet. (Should the Map be a static class field?)
- Another solution is to make the permanent ID field mutable an apply the appropriate synchronization. Additionally we could limit the ID to be set only once in the object's lifetime.
Are these solutions reasonable? Any other ideas? Thanks.
withX(..)as ColinD suggested or just synchronize as Stephen C suggested. There are some other issues involved such as application display (GUI or console). I think which way to go depends on how it will be used. In my case, I am still analyzing that.