« Excel OFFSET function is key to creating charts that track available data | Main | Design “issues” with .NET »

EventHandler and EventArgs pattern

Okay, so who out there knows what pain will follow breaking the recommended EventHandler / EventArgs design pattern?

As far as I currently know, it’s purely a convention and motivated by an ill-defined intent of being general enough to handle all possible event data signaling requirements with a fixed set of parameters.

There doesn’t seem to be any compiler or debugger issue with using any combination of arguments you like for your delegate.

I’m guessing the designers figured events have a way of wanting to pass more information back to their clients over time and we don’t want our users’ code to break everywhere when they change their parameter list. So let’s train them to use derived classes to hold the actual parameters and then they’ll be in a good position to add more data through derivation without breaking clients who don’t care.

The drawback of this approach is that most times you have to experimentally guess what the actual type of the “sender” will be and whether it will ever be null or not. The same goes for the EventArgs derived parameter ever being null. The rule is return a default constructed EventArgs when you don’t have any data to include.

The thinking must be that someday in the future, you’re event source will start returning an EventArgs derived object with interesting data in it. You’ll then start writing client code that expects the argument to be non-null and of the derived type. If you completely fail to code defensively when accessing the parameter, your new client code could break if it ever runs against old event source code (which might return null). Seems like quite a stretch.

 

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)