On Feb 20, 11:21 pm, "Bruce Wood" <brucew...@canada.comwrote:
I throw my hat in with Dale on this one. Sometimes you really do need
to do some long-running operation in a constructor, but you should
avoid it if you can.
If there is some object that you want to use over and over in your
class, and it takes a long time to build, you might think about using
lazy construction: initialize it to null, and then the first time you
need it, construct it.
Bruce,
I concur. If you're just initializing IDbConnection or IDbCommand
objects then fine. But, once you call Open or ExecuteReader or
whatever it immediately goes from minimal work to a significant time
consuming operation. That's work that may not be obvious to the
developer since the constructor doesn't have a descriptive name. If
the semantics of the class require a signficant operation for
instantiation then create an adequately named static factory method
that clearly describes what the operation might do.
I've brought up the example of the StreamReader before as something
that does not adhere to the framework design guidelines. It's
constructor will actually open a file, but no where in the
documentation is that made explicitly clear. To be fair, it can be
implied from looking at the exceptions it throws, examples, or by
noticing that the class doesn't have an Open method, but wouldn't it
have been better to just create a static StreamReader.Open method
which clearly indicates that a potentially significant operation is
happening?
Brian