D const design rationale

Robert Fraser fraserofthenight at gmail.com
Fri Jun 22 14:12:57 PDT 2007


I think the most important thing regarding const/final/invariant is simply to remove redundancy. If every combination/keyword/construct means only one thing when applied to a particular declaration,it drastically reduces complexity for the user. For example, having "final int x = 5", "const int x = 5" and "invariant int x = 5" all mean the same thing is difficult, because users don't expect that. Similarly, having:

struct Foo
{
int x;
int* y;
}

const Foo bar;

, in which bar.x can freely change, but *bar.y can't makes structs seem far different than classes - you can no longer replace one with the other (besides having to put in/remove a "new"), if it's const.

I think having three keywords is probably a good thing, as long as whenever they're applied they mean different things. Overlapping meaning and unexpected behavior is one of the big problems with C++ - what's "static" mean? About 5 things?

On that note, I think "invariant" should be changed to "immutable". At the cost of a new keyword and a new token, we get both backwards compatibility with class invariants and disambiguation.

As long as I'm throwing my cent out there, dare I mention in-parameter-passing-by-default again?

All that said, I think this is a far cry better than the C++ version (which I never even bothered to understand), and I'm starting to see the advantages of using const (why was it left out in C#? The Java devs mentioned at some point that if they had the chance to redo it without breaking backwards compatibility, they would have). So, thanks, Walter, for the great update! D is definitely the language to beat for anything bigger than a Perl script.

All the best,
Fraser



More information about the Digitalmars-d mailing list