Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice with Common Event Handling

In a WinForms solution, you have multiple controls of the same type. You need to add an event handler to each of the control and at the current time the event handler will be doing the same thing. You do not expect there to be difference between them down the road any reason.

eg:

ScheduledPatientsGrid.ProcessGridKey += ScheduledPatientsGrid_ProcessGridKey;
RecentPatientsGrid.ProcessGridKey += RecentPatientsGrid_ProcessGridKey;
RecentPatientsGrid.ProcessGridKey += RecentPatientsGrid_ProcessGridKey;

... 

private void ScheduledPatientsGrid_ProcessGridKey(object sender, KeyEventArgs e)
{
   ...
}

private void RecentPatientsGrid_ProcessGridKey(object sender, KeyEventArgs e)
{
   ...
}

private void PatientsGrid_ProcessGridKey(object sender, KeyEventArgs e)
{
   ...
}

Now is it better to sharing an single Event Handler between the different events as shown below or use different ones like in the code sample shown above?

ScheduledPatientsGrid.ProcessGridKey += ProcessGridKey;
RecentPatientsGrid.ProcessGridKey += ProcessGridKey;
RecentPatientsGrid.ProcessGridKey += ProcessGridKey;                


private void ProcessGridKey(object sender, KeyEventArgs e)
{
  ...
}

In the following page, Microsoft seems to suggest that sharing is better, however I notice that they have not updated it since .NET 2.0 (ie: Visual Studio 2008)

http://msdn.microsoft.com/en-us/library/4ac48519%28v=vs.90%29.aspx

Is there a Guide that makes a best practices recommendation in this case?

like image 847
Adrian Avatar asked Jan 26 '26 20:01

Adrian


1 Answers

I would absolutely use the same method. What possible benefit is there to having multiple methods which do exactly the same, none of which is named to say what it does?

Personally I abhor the source_EventName convention that Visual Studio spawns. I prefer to give my event handler methods meaningful names which say what they do. Then when you look down the event handler list in the designer, you can see that when a button is clicked, X will happen rather than "the button's click event handler will be called" which is useless.

Alternatively, use lambda expressions to subscribe to the events and call meaningful methods with meaningful parameters. (The sender and args are often useless for event handlers.)

like image 50
Jon Skeet Avatar answered Jan 28 '26 12:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!