thoughts on immutability in D

Peter Alexander peter.alexander.au at gmail.com
Thu Sep 22 09:40:34 PDT 2011


On 22/09/11 12:39 PM, bearophile wrote:
> Andrei Alexandrescu:
>
>> The initial submission got junked so I resubmitted:
>>
>> http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/
>
> A logical const can coexist beside the other two (three) kinds of const of D. For simplicity I use the "lconst" keyword.
>
> lconst works similar to the C++ const, and it gives not troubles, because it is orthogonal to the other true consts. You are allowed to safely cast away lconst and then change the variable contents. But if you change it without casting away lconst, the compiler complains statically. Is it better to design lconst too transitive? Maybe lconst is also a "head const" just like C++. This is probably handy enough. So with a lconst array you are allowed to change its contents, but not reassign it or change its length. A lconst doesn't implicitly cast to immutable.
>
> So I think this is well doable. And probably it is useful too. But having four kinds of const in D is a lot of stuff. Maybe it is too much complex.
>
> An alternative solution to face some of the needs of lconst is to define a "trusted pure" that allows to create a pure memoization (a pure memoize).

As much as I would like logical const, I think adding it would be a 
mistake. Every feature, no matter how simple, adds complexity to the 
language: it has to be implemented, maintained, understood by tools, 
taught, documented... Also, if you keep adding more and more qualifiers 
and attributes then eventually you spend more time describing the 
characteristics of your program rather than the program itself.

>> You're right. Logical const is only a convention, since it cannot be enforced by the compiler.
>
> Even if it can't be enforced in 100% of the cases, I think it's still useful. So you need to look at the situation from a bit wider point of view.

Yes, it is still useful, even if not to the compiler. It's like 
documentation that the compiler can semi-enforce.



More information about the Digitalmars-d mailing list