I have a DataStructure
class, which I want to be immutable.
Ordinarily, I'd just ensure that all my members are defined as readonly
- Job Done.
But one of the members is a list (of ints), so I need to ensure that the List
can't be modified; so I change it to a ReadOnlyCollection<T>
. Fine.
I also need that collection to be ordered in a certain way - again fine, I sort the list accordingly before converting it via .AsReadOnly()
.
So far, it's all been fine.
But the last step is that I want 3 different constructors - each accepting the original data in a different format. Now I have to duplicate the code that converts the list to the necessary format, in each constructor.
If I commonise it out into a setList()
method, then the variable can't be readonly
, because it's being assigned in a non-constructor method. Now I've lost some of the immutability.
Ideally, there would be some way that I can declare that the setList
method can only be called from a constructor, and thus is allowed to edit readonly
members, but I don't think that exists.
I could create wrap everything in getters and so forth, so that the class is immutable from the outside, but I'd rather like it to be immutable from the inside too (especially given that I can achieve this is I sacrifice DRYness)
Does anyone have any clever ideas about language features I've forgotten about that would solve this?
Rather than using a void SetList(List)
called from constructors, you could have a List PrepareList(List)
. This method would prepare the list, and return it to the callers -ie: the constructors.
So the code wouldn't be repeated -except an affectation _list = PrepareList(list)
in each constructors.