I think that “Doing work in the constructor” is okay…
… as long as you don’t violate Single Responsibility Principle (SRP) and stick to using Dependency Injection (DI).
I have been asking myself this question too lately. And the motivation against doing work in the constructor that I have found are either:
- It makes it hard to test
- All examples I have seen have been where DI wasn’t used. It wasn’t actually the fault of the constructor doing actual work.
- You might not need all the results that your constructor calculates, wasting processing time and it’s hard to test in isolation.
- This is basically a violation of SRP, not a fault of the constructor doing work per say.
- Old compilers have/had trouble with exceptions thrown in constructors, hence you shouldn’t do anything other than assign fields in constructors.
- I don’t think it’s a good idea to write new code taking historical compiler deficiencies into account. We might as well do away with C++11 and all that is good all together if we do.
My opinion is that…
… if your constructor needs to do work for it to adhere to Resource Acquisition Is Initialization (RAII) and the class does not violate SRP and DI is properly used; Then doing work in the constructor is A-Okay! You can even throw an exception if you’d like to prevent usage of a class object whose initialization failed completely instead of relying on the user to check some return value.