I totally disagree.
I'm not with the 'totally'. There are marginal cases where I've probably done this sort of thing with the one event handler. There are many reasons why I don't do it as a matter of course, however.
There's nothing wrong with handling all of a group of buttons in a toolbar with a common event handler. Makes it much easier to read and find later and subsequently work with.
It doesn't scale well. My current project uses a toolbar/menu system with >70 commands. The implementation of most of the commands are spread across a number of classes. If I were to use your example below, the code would be of unmanagable length.
Take this for example: (I'll use VB here) Select Case (True) Case (Sender = btnBold) 'Set bold Case (Sender = btnUnderline) 'Set underline Case (Sender = btnItalic) 'Set italic End Select This works so much better, especially since each of these is one line. I only have one place to look and I don't have to have 3 separate event handlers for what amounts to the same thing.
It works better *because* there are only 3. 3 items for a quick project probably is easier to maintain. I still wouldn't call it good design. You are introducing a dependency in the code that the compiler cannot check (whether there is a 1:1 mapping between buttons and handlers), which isn't so good. You are also associating code by how you reach it, rather than what it does - inappropriate, IMHO. You've lost the separation between the viewer (UI) and model (the underlying code object). As an illustration, how would you add key- board accelerators for actions currently provided via toolbuttons? You end up having to simulate the toolbutton being clicked (again, inappropriate IMHO). Your "amounts to the same thing" comment I still don't get, since I don't see any similarity in your implementations. However, if you do have very similar code, you can (now, in .Net 2.0) attach an anonymous delegate to the .Click event handlers calling a common function with an appropriate parameter (TextStyle?). The problem with starting with the simple solution is that by the time you realise that the code is too big to maintain, its a major job to change.
If it was so "daft" as you put it, then why do we have the capability? Why did MS put the idea of a "sender" in every event handler if it was never necessary, or required, or useful? Having the sender is daft as well by that reasoning.
Actually, it is essential for collections of objects - where the *behaviour* for each item is the same, but the actual object you're working with varies. As a simple example, an MRU list could share the same event handler (after all, each MRU item does the same task), but the actual object (and therefore the file that will be loaded) will differ between menu items. John =================================== This list is hosted by DevelopMentorĀ® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com
