How much work should be done in a constructor?

To summarize:

  • At a minimum, your constructor needs to get the object configured to the point that its invariants are true.

  • Your choice of invariants may affect your clients.(Does the object promise to be ready for access at all times? Or only only in certain states?) A constructor that takes care of all of the set-up up-front may make life simpler for the class’s clients.

  • Long-running constructors are not inherently bad, but may be bad in some contexts.

  • For systems involving a user-interaction, long-running methods of any type may lead to poor responsiveness, and should be avoided.

  • Delaying computation until after the constructor may be an effective optimization; it may turn out to be unnecessary to perform all the work. This depends on the application, and shouldn’t be determined prematurely.

  • Overall, it depends.

Leave a Comment