Alex Rivera | Logout

How much work should be done in a constructor?

Asked 2008-11-16T15:14:04.360
56

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 constructing an object that represents a directory structure should the population of the object and its children be done in the constructor. Clearly, a directory can contain directories and which in turn can contain directories and so on.

What is the elegant solution to this?

Edit
Report

3 Answers

10

It depends (typical CS answer). If you are constructing objects at startup for a long-running program, then there is no problem with doing a lot of work in constructors. If this is part of a GUI where fast response is expected, it might not be appropriate. As always, the best answer is to try it the simplest way first, profile, and optimize from there.

For this specific case, you can do lazy construction of the sub-directory objects. Only create entries for the names of the top level directories. If they are accessed, then load the contents of that directory. Do this again as the user expolres the directory structure.

answered 2008-11-16T15:23:09.897
2

As for how much work should be done in the constructor, I'd say it should take into account how slow things are, how you are going to use the class, and generally how you feel about it personally.

On your directory structure object: I recently implemented a samba (windows shares) browser for my HTPC, and as that was incredibly slow I opted to only actually initialize a directory when it was touched. e.g. First the tree would consist of just a list of machines, then whenever you browse into a directory the system would automatically initialize the tree from that machine and get the directory listing one level deeper, and so on.

Ideally I think you could even take it as far as writing a worker thread that scans the directories breadth-first, and would give priority to the directory you're currently browsing, but generally that's just too much work for something simple ;)

answered 2008-11-16T15:19:30.387
0

If something can be done outside a constructor, avoid doing it inside. Later, when you know your class is otherwise well-behaved, you might risk doing it inside.

answered 2008-11-16T17:57:51.677

Your Answer