tags:

views:

235

answers:

4

Was just thinking about this question while trying to figure out some code written by our previous developer. Trying to trace out how control of the program was happening reminded me of the bad old days of BASIC, where it was hardly ever obvious the execution path of a program. Is this more a symptom of event abuse, or is there a structual problem with the observer pattern?

+10  A: 

Like any technology, events can be used incorrectly and abused. However, since you didn't give any examples of your problem, it's virtually impossible for us to tell what you're talking about.

In general, no. Events are not the OO equivalent of GOTO, nor are they typically a problem. Nor is there any structural problem with the observer pattern that I'm aware of. But abuse can happen with anything.

GOTO's are bad for a lot of reasons, but one of the biggest ones is that it is a transfer of program flow, not merely a subroutine execution. When you use a goto, program execution does not return to the point after your goto call when it's done (or after it's been initiated in the case of an asynchronous event). Program flow is transfered permanently to the new execution point. What's worse, is that it can transfer execution to anywhere, including inside other control structures or other functions.

Events simply do not have these characteristics, and are little more than function pointers with object awareness and a publish/subscribe capability. (ok, there's a lot more than that, but this is their basic usage)

Mystere Man
+3  A: 

No, it isn't. Goto is...ahm...I'm afraid of raptors...

Events are nothing more than a list of delegates which get called one by one. F.e.:

-> Click Event gets called
    -> List of associated Event-Handlers
        -> Calls every Event-handler/Delegate in the List
Bobby
+1 for xkcd reference
jrummell
A: 

The worst thing that I've seen with events is the calling of multiple other events within an event. One colleague that I worked with did this constantly. I think that may be a situation that can be difficult to traverse through, but it's still more readable than GOTO.

Aaron
A: 

To answer your question, events are not the OO equivalent of GOTO, as GOTO in itself is a reserved word. Events are different, Events follow the fire and forget paradigm where GOTO is "fired but handled procedurally" within the code. Usage of GOTO can lead to abuse resulting in spaghetti code. Nonetheless, the only time GOTO may be used is in an error recovery situation WITHIN the scope of the method/or function. Whereas Events can be consumed by many receivers, GOTO is consumed by one only.

It might be worth your while to use AOP framework such as PostSharp where you can get the AOP injected into your code at runtime in order to see the flow and trace of the events to help understand the code better.

Hope this helps, Best regards, Tom.

tommieb75