mutable, const, immutable guidelines

Ali Çehreli acehreli at yahoo.com
Tue Oct 8 21:41:35 PDT 2013


On 10/08/2013 03:03 PM, qznc wrote:

 > On Wednesday, 2 October 2013 at 13:09:34 UTC, Daniel Davidson wrote:
 >> 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 think guideline 1 should be about "arguments" not "variables".
 > Functions should take const arguments, so they can be called with
 > mutable and immutable values.

As demonstrated in the presentation, const erases the actual type. So, 
the function must take a copy if the argument is to be used in an 
immutable context.

Instead, if the immutable appears on the interface, that copy will be 
avoided.

 > I would rephrase the second guideline as: "Never dup or idup an argument
 > to make it mutable or immutable, but require the caller to do this
 > (might be able to avoid it)".

Agreed. But it means you agree with me that immutable should indeed 
appear on function signatures as needed.

 > For more guidelines:
 >
 > 3. Return value, which are freshly created, should never be const. They
 > should be mutable or immutable.

Agreed. I say that it should be mutable if the function is pure, as such 
a return values is automatically convertible to immutable.

 > Basically, I cannot come up with a case, where const would be preferable
 > to mutable and immutable. Maybe someone is able to find a good example?

You mean on the return type? Perhaps if the freshly created object 
carries references to existing data that you don't want mutated. Making 
the head const makes tail const; so the members would all be protected.

However, it is always possible to return a mutable object of a type that 
has const members:

struct Result
{
     const(int)[] reference_to_precious_existing_data;
}

Result freshly_created_value()
{
     // ...
}

 > Of course, this does not hold for returned values, which are retrieved
 > from somewhere (array,container,etc). In this case, I have no general
 > advice.
 >
 > 4. Data structures should not restrict themselves to be mutable, const,
 > or immutable.

What is the template of a struct that can be used as such? Providing 
simple values seems to be insufficient:

struct MyInt
{
     int i;
     private int[] history;
}

What else should the struct above have to make it usable as mutable, 
const, immutable?

 > This is a noble goal, which in reality is probably either trivial or
 > impossible. So I am not sure, if it is worthy to be called a guideline.

We have to nail this down already. We have this great addition of 
immutable in the language but we either don't know how to use it or the 
language is lacking hopefully trivial things to make it work.

Ali



More information about the Digitalmars-d-learn mailing list