3

In ActionScript the URLLoader class that has seven separate events than can occur after you call the load() method.

In the HTTPServive classes there are two events, fault and result.

In one of the classes I've wrote there is only one event, result. In the result event I have property success that is set to true or false and if true the event has additional properties set. If false it has error object set.


To generalize, in the first class an event is dispatched for very specific cases. In the second class there are only two cases, success or failure. In the last is one event that contains, success, failure, errors everything all in one.

I'm now reading about callback hell when dealing with asynchronous calls and how the then function can help with that. It will call a success or failure callback function on the results.


My question, is what are the pros and cons of writing a class that dispatches many very specific events vs dispatching fewer events and what would you like to use daily as a developer?

Note: This is regardless of the language and more of the approach one handler to handle multiple cases or multiple handlers to handle each individually.

3

All these approaches are fine, they cover different use cases.

Event defines a moment of time when something happens. Handler defines a type of information associated with a given event.

In that sense both success and failure handlers are handling one event - result arrival. Success and failure outcomes are mutually exclusive and represent a special case of event handling - it (almost always) makes no sense to handle one outcome while leaving another unhnadled. This in turn means that a proper API would disallow registration of one without another. A fine example of such API are Promises which always handle error case implicitly.

Of course, nonexclusive outcomes are not subject for such treatment and therefore are handled by designated handlers registered separately. For example, you may want to only be notified about final document arrival and do not subscribe to progress notifications.

It is perfectly fine to only have one handler, such handlers are often used in Databinding frameworks, where errors terminate processing stopping event propagation, leaving no need to update derived values.

Group your handlers by a moment when their event happens (usually each group would turn out to be mutually exclusive) provide an API to register handlers for each group. Provide one handler per outcome, so that you won't have a dispatch over event object type within handlers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.