I realize this question has been asked several times, but I wanted to frame it in a particular example that I am working on here. I am working on a finite element code, which operates on a mesh. A mesh is logically an object, and one can do nothing with it until it is “constructed”, or built. It seems to make sense, then to pass the mesh parameters to the constructor and have the constructor build the mesh. Searching around the web, I see a general opinion that this isn’t a good idea necessarily, and that the constructor should do as little as possible.
Mesh generation can be a long, complicated process. On the other hand, the mesh is completely unusable until it has been generated, which I would consider its construction. I could map out each step as a method I expect the client to call, but those methods will always be the same, and they will always use the same parameters. Even if internals change, it is extraordinarily unlikely the public interface will. Furthermore, it probably makes sense that the client shouldn’t be concerned with the mesh generation specifics. With that in mind, it seems to make sense to have the mesh completely generated in the constructor, and in a ready to use state afterwards. I could also create a simple generate method that is opaque to the client, but then why couldn’t the constructor do the same thing? It has to to be usable.
Is there a hidden danger here that I should be aware of in putting this stuff in the constructor?
The constructor needs to build the “essential” building blocks or elements that will be used within your methods afterwards. If the majority of your methods work on the mesh, I would use the constructor to generate the mesh. On the other hand, if most of the methods can work on smaller elements than the mesh, then maybe you shouldn’t wrap it under the constructor.