mutable, const, immutable guidelines

Daniel Davidson nospam at spam.com
Wed Oct 16 12:45:09 PDT 2013


On Wednesday, 16 October 2013 at 19:12:48 UTC, Dicebot wrote:
> On Wednesday, 16 October 2013 at 19:06:06 UTC, Daniel Davidson 
> wrote:
>> I don't understand how it could be fine. As code grows it 
>> would lead to people not adding useful members like history 
>> just because of the huge repercussions.
>>
>> struct User {
>>   immutable(Foo) foos;
>> }
>>
>> How can I as a user adapt to that change? Before the change 
>> assignment worked equally well among all of Mutable, 
>> Immutable, Const. After that change any `foos ~= 
>> createFoo(...)` would require change. And it is not clear what 
>> the change would be.
>
> I think any usage of immutable with types/entities not 
> initially designed for immutability is an potential mistake and 
> in that sense it is good that change has broken the user code. 
> Same goes for operating on immutable entity in generic code as 
> if it is a value type without actually checking it via 
> introspection.

I don't disagree. Now, what does it mean to "initially design for 
immutability" and what are the guidelines. I thought that was 
kind of what we were talking about here. How to effectively use 
const and immutable. If the rule is - don't use immutable unless 
you have immutability in mind for your design, ok. Maybe take it 
a step further...

How about this - show a good use of immutable in any context 
where mutable aliasing (e.g. AAs) are in the mix. If the response 
is there are none, it is just too hairy of a proposition then 
something is wrong.

One general idea that was presented by Ali is that an immutable 
parameter means that not only are you guaranteeing that you will 
not change your data, but also that no one else, even in another 
thread will. That sounds appealing. After all, who doesn't want 
the data they are using in a function to not change from 
underneath them? Suppose you have highly structured, deeply 
nested reference data you read from a nosql DB. Surely there is 
opportunity and some benefit to use immutable? The result of the 
query is just a read only data source. But then that data will be 
consumed - presumably by functions with either immutable or const 
parameters. If all signatures use const then when can you benefit 
from the fact that the data is really immutable (by the time it 
gets to a function with const parm the fact that it really was/is 
immutable is lost.


More information about the Digitalmars-d-learn mailing list