Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a bad idea to use event handler method signatures deviating from sender and eventargs?

The code analysis tool in VS 2012 has suggested a few problems with my code. Most are fine, This one (CA1009 Declare event handlers correctly) however I can't understand the reasoning for.

If I don't need any data, just to know that something has occurred, it seems to me that I'm obfuscating my real intentions by using events with unneeded parameters.

For example, say I want to list all customers who match a given criteria. If my repository is updated, I need to recheck the data.

So I create a repository class, then give it a DataChanged event with the following signature:

public event Action DataChanged;

Then in one of the classes using the repo I can do

repository.DataChanged += UpdateMatchingCustomers;

private void UpdateMatchingCustomers() {
    MatchingCustomers = ...
}

Why is this a bad idea?

like image 365
Jamie Wroe Avatar asked Oct 05 '22 12:10

Jamie Wroe


1 Answers

I think the main idea is that somebody might want to use the same event handler method to handle events from multiple sources, and having a matching signature is helpful:

  • Enforcing the existence of sender makes sure the handler can distinguish between different event sources
  • Having all the event data objects derive from EventArgs ensures that there's always a proper type to use for the data argument

Additionally, having a base class for event data and enforcing it ensures that classes that extend the event source can send more data with the existing event than the base class, and this makes sure it's possible (granted, this is a bit far-fetched, but I have done this at least once in an actual program).

I also wouldn't be surprised if some of Microsoft's fancy designers (they sure love them designers) broke if an event didn't follow their expected pattern.

like image 66
Matti Virkkunen Avatar answered Oct 10 '22 03:10

Matti Virkkunen