How is Java inheritance being used to enforce program requirements?
I was looking at a blog about good API design here
In one of the example sections titled 'Reinventing the Socket', it showed a design of how to enforce certain rules and prerequisite on the client code that uses it. eg. the client must call bind() before it can call connect(), and it must be connected before it's allowed to send() or receive() data.
I'm more familiar with C/C++ so I'm having some trouble fully comprehending how the class design is enforcing the API rules. Like for example, how do you prevent client code from making calls into this API with something like this:
How and why would the compiler catch that error? If I'm understanding the subclass inheritance correctly, SocketConnected is-a SocketBound which is-a Socket. But if the client code is able to declare a SocketConnected object, how can you enforce the rule that bind() and connect() must be called before send() and receive() are allowed?
SocketConnected s = socket.bind(localaddress, 1000);
//client doesn't call the connect() method
//and just calls the send() method right away.
//this line should give compile-time error
//because only bind() was called but not connect()
s.send(/* some data goes here */);
I get what most of the code is doing but the part that confuses me is near the bottom where the author says:
How could that type of usage be equivalent to
SocketConnected s = socket.bind(localAddr, 1000).connect(remoteAddr, 70)
Also is there a design pattern that generalizes this example?