Tuesday, September 6, 2011

The very structure of the code.


If I have a simple socket interface

public interface ISocket
        {
            public bool Connect(IPAddress address);
            public bool Read(Buffer b, int size);
            public bool Write(Buffer b, int size);
        }
       
It can already be abused, The calling code could Read or Write without doing a Connect.

What if I change the very structure of the code to reflect the constraints I want to impose

        public interface ISocket
        {
            public bool Read(Buffer b, int size);
            public bool Write(Buffer b, int size);
        }

        public interface ISocketFactory
        {
            public IScoket Connect(IPAddress address);

        }


Now, once you have an ISocket, you KNOW it's was at one point connected, It has an associated IPAddress.
The other side may have disconnected since, but that's a whole other matter.

We have now made it more or less impossible to read or write to a socket which is uninitialised.

Of course you could put the IPAddress in the constructor of the Socket, but for our nice generalised code base, that is a problem, since we now have to know which type of socket we want to create. Once we start doing "new IPSocket(serverAddress)" in our class, we can change to using some other type of connection, eg TestSocket() or QueueSocket() which we might want to use if the other side is in process.


No comments:

Post a Comment