Why D const is annoying

Steven Schveighoffer schveiguy at yahoo.com
Wed May 2 05:19:08 PDT 2012


On Tue, 01 May 2012 23:30:27 -0400, Mehrdad <wfunction at hotmail.com> wrote:

> Also, I think you didn't notice the other problem.
>
> The other problem was with IConnection, whose send() wasn't 'const',  
> which also gives you an error due to the transitivity of const (which  
> I've also claimed is broken).
> And how could it? It's just a connection, not a server, so it doesn't  
> parse the input... and it probably changes the state of the connection,  
> since connections often have internal buffers they need to modify (if  
> not prioritization, etc.).
>
> So, what is D's solution for _that_ problem?

There are two solutions, both are horrible.

1. Cast. Coder beware.
2. Store conn outside the instance (i.e. in a hash lookup).  Horrible.

There is a possible 3rd solution.  Don't use immutable/const, instead use
information hiding.

In other words, Your class is already technically "immutable", since name
will never mutate beyond the first setting.  This requires coder
discipline, and has no help from the compiler.

But many languages that *don't* have const/immutable do well with this
pattern (think Java strings).

I have periodically mulled the idea of making a library-based solution for
logical const.  I think it would work, but you would have to be extremely
cautious, and you lose some compiler guarantees for it.

The most difficult part to deal with is how to prevent concurrent access,
when an immutable object is always implicitly sharable.

I have another idea which gets around the problem in a different way.  I
think it's essential to bringing arbitrary ranges in line with current
array features.  When I have some time to flesh it out, I'll propose it.
I think we absolutely can't be finished with ranges until this is
implemented.

-Steve


More information about the Digitalmars-d mailing list