Immutable Collections
I just saw an interesting post that talks about a general pattern of immutable reference types. Good read. I highly recommend it!
At the end of the post the author suggests that we add “value object” generic collection to the BCL. It’s an interesting suggestion, but unfortunately not as easy as it may seem. The difficulty lays in the fact that the items in such collection also need to be immutable. String is an immutable collection of characters, which are immutable themselves.
One way to design this would be to add IImmutable marker interface, implement it on immutable types, and constrain the proposed ReadOnlyList<TImmutable> to TImmutable : IImuttable. Now, I am not sure the value of doing this outweighs the added complexity, but we will take a closer look.
Comments
- Anonymous
November 22, 2005
The comment has been removed - Anonymous
November 22, 2005
Not to mention that there is no way to enforce the contract that such a marker interface would attempt to imply, which would make it useless if deep in your object you've got a falsely-marked class. Seems like an interesting thing to do would be to examine TImmutable for members that cause mutations. Perhaps at runtime through a naive "look for property setters through reflection" approach, or have the compiler mark the type using some stronger code analysis (looking for stfld instructions outside the constructor seems like a straighforward approach) - Anonymous
November 23, 2005
Yes, the easiest thing would be not to have a built-in enforcement of the contract. The interface would be just an indication to the developer (through the constraint) that they are using the collection properly.
I can imagine the verifier checking the contract (as you described by looking for store instructions), but that raises the complexity of the feature even more. - Anonymous
December 08, 2007
Oh dear! TAG you are wishing const modifier (C++) on member functions.