Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad Practice to run code in constructor thats likely to fail?

Tags:

People also ask

How can I handle a constructor that fails?

The best way to signal constructor failure is therefore to throw an exception. If you don't have the option of using exceptions, the "least bad" work-around is to put the object into a "zombie" state by setting an internal status bit so the object acts sort of like it's dead even though it is technically still alive.

Is doing a lot in constructors bad?

So yes, doing a lot in constructor is a bad idea in my opinion. Generally I just put some field initializations into the constructor and make an init method to invoke when everybody is on board. I think that your problems may have been caused by violation of SRP and not the constructor doing actual work. – Emily L.

What happens if constructor fails?

If an exception is thrown in a constructor, the object was never fully constructed. This means that its destructor will never be called. Furthermore, there is no way to access an object in an error state. The exception will immediately unwind the local variable.

Is it good practice to throw exception in constructor C++?

Yes. That's precisely how a constructor signals that something went wrong and the object could not be constructed properly. A constructor is responsible for completely initializing the object in a valid, usable state. If it can't do this for some reason, there is no way to return a value to the caller.


my question is rather a design question. In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:

someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.

I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :

  1. is attribute really set?
  2. do some IO actions to fill the attribute
  3. return the contents of the variable in question

I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.

Whats a proper way of doing this?