Friday, April 15, 2011

Is there Beauty in Events?

There is a question that comes to mind - Is there beauty in events? In using events, do you feel like they are just a giant mess? This tends to happen to me anyway. Event driven software is much of what I find myself doing with C# nowadays. Somehow, I am able to code rapidly with events but the overall feel of the code is more like a monster that just keeps growing and growing. This is probably from a lack of understanding of how to implement them beautifully or efficiently. I would love to consider this more...How to develop event driven software that doesn't feel like I'm just creating events all over the place.

With the help of Visual Studio, it appears that you can now auto create an event handler just by typing in the name of an event somewhere in a xaml tag or somewhere in the code-behind and then by simply pressing the tab button. This auto-generates your event handler with a generic name. Talk about creating easy to read code (sarcasm) ;). Thanks Microsoft...okay so it could be a bad tool if you don't take into account how visual studio creates these event handlers. It appears to take the name of the calling object/class followed by an underscore and then the name of the event. This is pretty slick but can also make for some unfortunate misunderstanding in code.

What if you could use one event handler for several objects?? This seems to be the biggest problem for me when using this tool! If you have a single event handler for objects such as a Border and a Grid then when you use the auto-generate tool for the first object it will come with the name of the Border or Grid class which you selected.

For example, suppose you had the following Border defined in xaml:

<Border BorderThickness="1" Margin="0,42,2,-69" Width="146" HorizontalAlignment="Right" RenderTransformOrigin="0.396,0.59" MouseEnter="Border_MouseEnter" MouseLeave="Border_MouseLeave" Grid.Column="5" Grid.ColumnSpan="2">

and the following Grid also definded:

<Grid Height="150" Width="150" MouseEnter="Border_MouseEnter" MouseLeave="Border_MouseLeave" Margin="-1,7,7,7">

Do you see the problem? Both the Border and the Grid are using the same event handler but the name of the event handler leaves you with a feeling of discomfort. The Grid isn't a Border and therefore makes you wonder why should a Grid have a Border event handler. This is an ambiguity that for truly beautiful code shouldn't be ignored. While the Microsoft tool is great..the point is to use it with the dignity to make your code clear. Be careful in the way that you use it in order to create a more healthy clean environment :). Or something like that...


No comments:

Post a Comment