Transitive const sucks

Alex Burton alexibu at mac.com
Tue Sep 11 02:56:29 PDT 2007


While const is being reexamined....

I create an interface :

interface Server
{
    Data getData() const;
};

I then write half my application using a stub implementation of Server, which is refered to using const references, because this application doesn't modify the server (the interface has no non const members).
Then the time comes to implement the Server properly using a socket to communicate with a server.

interface Socket
{
    void send(const Data d);
    Data receive() const;
};

class ServerImplementation : Server
{
    Socket sock;
    Data getData() const
    {
        sock.send(request);
        return sock.receive();
    }
};

My application doesn't compile because I am refering to using const Server references every where, and it turns out the server class needs to modify it's socket to implement the getData method.

This is wrong.
The socket is not part of the ServerImplementation, it's just that D can't tell the difference between things that are part of a class and things that are not.
I now have to make the getData method non const and all the references to Server non const, and possibly not use any const references in my application again, as similar examples can be constructed for all sorts of things, and basically the const system does not work.

I think it's great to search for a better const system that c++, but if you have a great system for allowing compiler to optimise, but the programmer can't actually use the system to describe reality then it's not better at all.

The solution is to be able to say whether the socket is part of the server or not, then the const system can be made to work, as it did in c++.
I am not saying that c++ const is great but at least I can use it to describe reality (although it's cumbersome, and there are a lot of reasons why I am itching to convert all my stuff to D).

Sincerely,
Alex



More information about the Digitalmars-d mailing list