Immutable Object

I think there is another way to make an immutable object without creating lots of copies of interfaces and things. If I don't want people to change my Transaction objects once they have been created, I have only one method that sets any of the instance variables, e.g., initializeName:date:amount:etc. It uses lazy initialization to ensure it gets set only once.

If the object is not truly immutable, then there are legal occasions on which it may be updated. The big question is, who controls who may update it and when they may do that?

Agreed - most truly Immutable objects have their attributes set only in a constructor, and rely on language rules to prevent the constructor from being invoked more than once. That makes this whole concept an Idiom, which works great in languages such as Java Language and Cee Plus Plus.

You bring up another, related issue, of separate interfaces for separate clients. Robert Martin has written an article in Cpp Report describing Private Interface, a pattern for this. The idea is that only certain clients would have access to certain setter methods for an object. The paper that describes it is in the publications section of www.objectmentor.com .


See original on c2.com