|
-
January 18th, 2002, 06:38 PM
#4
Re: a question on class design
To add to Anavelepo:
It is not a good design to have your constructors do so much work.
a) What if the Parse fails? How would you know? You did create an object, but it is now unstable because some part of the contructor failed.
b) What if you pass these objects or use them in such a way that the compiler has to create temporary copies of the object? The constructors for the temp versions have to be called, meaning the Parse has to be called. This results in your code slowing down to a crawl if it is used in any relatively OO manner.
Constructors that do too much are *not* considered good class design for the reasons stated above. Can you imagine a constructor that opens a 1 megabyte file and reads it into a buffer, parses the file, etc.? Believe it or not, I've seen horribly written code that does this.
Constructors are meant for *simple* initializations, not for implementing whole sequence of operations that are expensive in terms of time or complexity. Stick with the model of doing this in two steps:
1) create a derived object, with the construtor just initializing simple member variables, so as to set the object in a valid "constructed" state. Maybe have a bool member that on construction is set to false, signifying that the Parse has not been initiated.
2) Then in a separate public function, the user of the class must call Parse() to actually start the parser. Set the bool member to true if Parse() is successful.
I once had to work on a problem where the programmer did almost exactly the same thing as what you are doing. The problem was that the constructor did so much work, but part of that work was failing. So an object was created, but it was unstable to use since the constructor failed. Don't fall into this trap.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|