const or immutable?

Ali Çehreli acehreli at yahoo.com
Thu Sep 23 22:57:57 UTC 2021


On 9/22/21 2:34 PM, Kagamin wrote:
 > My guideline is that most stuff is mutable, so there's little reason to
 > try to make it const.

I've been putting const as much as possible:

   const arr = foo();

However, as soon as I decide to mutate the result, I change it to auto:

   auto arr = foo();
   arr[0] += 42;

So, defensive programming prescribes 'const' and it seems like I did 
protect myself from accidental mutation. But how common are these 
accidental mutations? Is it so common to worth the neural activity and 
needing to change the code when it's not an accidental mutation?

As I hinted in some of my DConf presentations, I started to question the 
value of some programming constructs. For example, I don't use 'private' 
unless a type gets complicated enough to protect its invariants.

I agree that 'private' is useful for API types to change implementations 
freely but I still question: If I already documented how to use the API, 
even with examples; but the users went ahead and reached inside and used 
members of my API structs... I am in the opinion that if I still have 
the right to change the implementation. I don't think it's the end of 
the world if the users have to change their code.

 > For most simple types like scalars and arrays
 > const is relatively cheap and useful, but its usefulness decreases with
 > complexity of the type, the more complex is the type the more likely
 > it's mutable. Strings often benefit from immutability.

There are cases where I remove a 'const' just to make the code compile 
instead of fighting the type system and it just works.

The fact that I am embarrassed to write these must be telling: Either I 
am becomming more and more mediocre as a programmer (as I gain more 
experience!), or maybe there is something else here. :)

Ali



More information about the Digitalmars-d mailing list