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.


You usually do not want the constructor to do any computation. Someone else using the code will not expect that it does more than basic set-up.

For a directory tree like you're talking about, the "elegant" solution is probably not to build a full tree when the object is constructed. Instead, build it on demand. Someone using your object may not really care what is in sub-directories, so start out by just having your constructor list the first level, and then if someone wants to descend into a specific directory, then build that portion of the tree when they request it.


The time required should not be a reason not to put something into a constructor. You could put the code itself into a private function, and call that out of your constructor, just to keep the code in the constructor clear.

However, if the stuff you want to do is not required to give the object a defined condition, and you could do that stuff later on first use, this would be a reasonable argument to put it out and do it later. But don't make it dependant on the users of your class: These things (on-demand initialization) must be completely transparent to users of your class. Otherwise, important invariants of your object might easily break.