How much work should be done in a constructor?

后端 未结 18 1133
离开以前
离开以前 2020-11-27 17:40

Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.

For example when constructi

18条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 17:57

    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.

提交回复
热议问题