tags:

views:

34

answers:

2
Work = New ExampleWork()

Here the Work is a withevents variable and I've used the handles clause for handling various events fired by the ExampleWork object. However the event handler will not get assigned till the constructor of the ExampleWork returns. Now how can I handle any events fired from the constructor? I can move the constructor logic out to a separate method and call it after the constructor has returned and thus handle all the fired events including events fired from constructor. However it doesn't look good. What is the best way to handle such a situation?

A: 

Ignoring the VB syntactic sugar for event handling, if an object is raising events on itself during its construction, that's a design smell. There are only two ways that those events could be subscribed:

  • The object could be exposing itself to the outside world while it's still being constructed, e.g. via a callback or static method call. This is generally a bad idea - if an object is still being constructed, it generally can't be considered to be "ready to use". In particular, there may still be a more-derived constructor body still to be called.

  • The object could be handling the events itself. This isn't quite so bad, but those event handlers still need to be aware that they're going to be called on a partially-constructed object.

Basically, try to avoid events being raised on an object during construction. Ideally, make the constructors themselves nice and simple, leaving the object in a valid initial state.

Jon Skeet
A: 

One way to handle this is with a form or class boolean variable such as "loading", for example, that is initialized to false dim loading as boolean = true. Then set it to true after the load or initialization is complete. Check for the flag inside the offending event handlers.

I agree that this behavior is a design smell, but the design could be Microsoft's, as it sometimes occurs with the trackbar or numericupdown controls. I would definitely check Tony's suggestions before implementing a messy flag like this, though.

xpda