Concrete Example: Abstraction of a controlling unit, which could also be a remote unit represented by a socket. For ease of use, I consider creating the sockets and accept()’ing already in the constructor.
However, this feels slightly weird. Such a constructor could always fail. And it could block. Is there a way that doesn’t make me uncomfortable, or is it just OO and I have to take that pill?
(This question relates especially to the trendy OO languages and the generally accepted styles used there)
While it is not necessarily bad to lock on a constructor, I would consider hiding that from the user. Something like:
From user code, if they see:
It seems sensible that a connection is established and the active connection is returned. Users expect the code to possibly fail (exception) or block, so there will be no surprises there, considering that in many libraries the creation of a
socketis a non-blocking call.Note: in this code
connectionrepresents an active connection, the library should control whether theconnectioncan be created directly or not, whether it can be closed (by anything other than the destructor, i.e. whether aconnectionobject can be alive and not represent an active connection) and whether it can be copied or not and what the semantics are.