Question

I tend to keep my objects consistent during their lifetime. In some cases, setting up an object requires multiple calls to different routines. For example, a connection object may operate in this way:

Connection c = new Connection();
c.setHost("http://whatever")
c.setPort(8080)
c.connect()

please note this is just a stupid example to let you understand the point. In between calls to setHost and setPort the object is inconsistent, because the Port has not been specified yet, so this code would crash

Connection c = new Connection();
c.setHost("http://whatever")
c.connect()

Meaning that it's a requisite for connect() to have previous calls to both setHost and setPort, otherwise it won't be able to operate as its state is inconsistent.

You may fix the issue with a default value, but there may be cases where no sensible default may be devised. We assume in the later example that there's no default for the port, and therefore a call to c.connect() without first calling both setHost and setPort will be an inconsistent state of the object. This, to me, points at an incorrect interface design, but I may be wrong, so I want to hear your opinion.

Do you organize your interface so that the object is always in a consistent (i.e. workable) state both before and after the call ?

Edit: Please don't try to solve the problem I gave above. I know how to solve that. My question is much broader in sense. I am looking for a design principle, officially or informally stated, regarding consistency of object state between calls.

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top