Why does Microsoft advise against readonly fields with mutable values?
Posted
by Weeble
on Stack Overflow
See other posts from Stack Overflow
or by Weeble
Published on 2010-05-10T17:18:36Z
Indexed on
2010/05/10
17:34 UTC
Read the original article
Hit count: 287
c#
|immutability
In the Design Guidelines for Developing Class Libraries, Microsoft say:
Do not assign instances of mutable types to read-only fields.
The objects created using a mutable type can be modified after they are created. For example, arrays and most collections are mutable types while Int32, Uri, and String are immutable types. For fields that hold a mutable reference type, the read-only modifier prevents the field value from being overwritten but does not protect the mutable type from modification.
This simply restates the behaviour of readonly without explaining why it's bad to use readonly. The implication appears to be that many people do not understand what "readonly" does and will wrongly expect readonly fields to be deeply immutable. In effect it advises using "readonly" as code documentation indicating deep immutability - despite the fact that the compiler has no way to enforce this - and disallows its use for its normal function: to ensure that the value of the field doesn't change after the object has been constructed.
I feel uneasy with this recommendation to use "readonly" to indicate something other than its normal meaning understood by the compiler. I feel that it encourages people to misunderstand the meaning of "readonly", and furthermore to expect it to mean something that the author of the code might not intend. I feel that it precludes using it in places it could be useful - e.g. to show that some relationship between two mutable objects remains unchanged for the lifetime of one of those objects. The notion of assuming that readers do not understand the meaning of "readonly" also appears to be in contradiction to other advice from Microsoft, such as FxCop's "Do not initialize unnecessarily" rule, which assumes readers of your code to be experts in the language and should know that (for example) bool fields are automatically initialised to false, and stops you from providing the redundancy that shows "yes, this has been consciously set to false; I didn't just forget to initialize it".
So, first and foremost, why do Microsoft advise against use of readonly for references to mutable types? I'd also be interested to know:
- Do you follow this Design Guideline in all your code?
- What do you expect when you see "readonly" in a piece of code you didn't write?
© Stack Overflow or respective owner