mutable, const, immutable guidelines

Ali Çehreli acehreli at yahoo.com
Mon Oct 7 10:57:11 PDT 2013


On 10/02/2013 10:07 AM, Ali Çehreli wrote:

 > On 10/02/2013 06:09 AM, Daniel Davidson wrote:
 >
 >  > I'm reviewing Ali's insightful presentation from 2013 DConf. I
 >  > wonder has he or anyone else followed up on the concepts or
 >  > formalized some guidelines that could achieve consensus.
 >
 > I have not followed up on those concepts.
 >
 >  > 1. If a variable is never mutated, make it const, not immutable.
 >  > 2. Make the parameter reference to immutable if that is how you 
will use
 >  > it anyway. It is fine to ask a favor from the caller.
 >  > ...

I have to report that I am not finding much time to go deeper in these 
issues. However, I spent some time this weekend, gaining a hint of 
enlightenment.

immutable is a requirement on two concepts, second of which is new to me:

1) As it is commonly known, it is a requirement that the data does not 
mutate.

2) It is also a requirement on the type that the variables of that type 
will always be usable as immutable. I have not formalized "be usable" 
yet but what I mean is that the type cannot be modified in the future in 
a way that inhibits its use in existing code.

To look at just one usage example, the following line carries two 
requirements:

     auto a = T();
     immutable b = a;

1) b will be an immutable copy of a.

2) T will always be usable as in that fashion.

If T appears on an API, it is the responibility of the user to ensure 
whether they are allowed to treat T in that way. Otherwise, they risk 
maintainability if the module decides to change T in any way that fits 
the module's needs. If they have not yet advertised that T can be used 
as immutable, it should not be.

So, the question is how can a module expose a type that can always be 
used as immutable? Can the module guarantee that its future needs will 
never disallow T's use as immutable (e.g. by inserting mutable 
references into the type)? Can the library always guarantee that T can 
be used as immutable by improving its definition, e.g. by adding 
necessary opCast, opEquals, 'alias this', constructors, etc?

I don't know these answers... :/ (yet! :p)

Ali



More information about the Digitalmars-d-learn mailing list