I'd like to add my own experience there.
I won't say much about the traditional debate Constructor/Init... for example Google
guidelines advise against anything the in the Constructor but that's because they advise against Exceptions and the 2 work together.
I can speak about a Connection
class I use though.
When the Connection
class is created, it will attempt to actually connect itself (at least, if not default constructed). If the Connection
fails... the object is still constructed and you don't know about it.
When you try to use the Connection
class you are thus in one of 3 cases:
- no parameter has ever been precised > exception or error code
- the object is actually connected > fine
- the object is not connected, it will attempt to connect > this succeeds, fine, this fails, you get an exception or an error code
I think it's quite useful to have both. However, it means that in every single method actually using the connection, you need to test whether or not it works.
It's worth it though because of disconnection events. When you are connected, you may lose the connection without the object knowing about it. By encapsulating the connection self-check into a reconnect
method that is called internally by all methods needing a working connection, you really isolate the developers from dealing with the issues... or at least as much as you can since when everything fails you have no other solution that letting them know :)