How much work should be done in a constructor?

后端 未结 18 1101
离开以前
离开以前 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 18:00

    Excellent question: the example you gave where a 'Directory' object has references to other 'Directory' objects is also a great example.

    For this specific case I would move the code to build up subordinate objects out of the constructor (or maybe do the first level [immediate children] as another post here recommends), and have a separate 'initialize' or 'build' mechanism).

    There is another potential issue otherwise - beyond just performance - that is memory-footprint: If you end up making very deep recursive calls, you will likely end up with memory problems as well [since the stack will be keeping copies of all the local variables until the recursion finishes].

提交回复
热议问题