开发者

Is there such a thing as too many events?

public class Human
{
    public void Run(){}
    public void Jump(){}
    public void Eat(){}

    //Generalized approach
    public EventHandler<HumanActivityProgressChanged> ActivityProgressChanged;
    public EventHandler<HumanActivityCompleted> ActivityCompleted;

    //Per-method approach
    public EventHandler<HumanActivityProgressChanged> Running;
    public EventHandler<HumanActivityCompleted> Ran;

    public EventHandler<HumanActivityProgressChanged> Jumping;
    public EventHandler<HumanActivityCompleted> Jumped;

    public EventHandler<HumanActivityProgressChanged> Eating;
    public EventHandler<HumanActivityCompleted> Ate;
}

I have different methods that implements Event-based Async pattern. These methods trigger a ProgressChanged eventargs and a Completed eventargs开发者_JAVA百科. They all trigger the same eventargs (As shown in the code above).

Does it make sense to provide an event per each async method? Or just provide a generalized event for all async methods? Is there such a thing as too much events?


Both are valid. It really depends on what your intention is.

Will you expect a listener to want to listen to all events and repond in similar ways? Go fot the generalized event.

If you are expecting a load of disparate listeners each interested in different aspects, performing wildly different tasks on these events, go for the second.

The idea behind api design is not to impose a certain way of usage on the clients (Rails users may disagree), but you will give strong hints in the way you design it..


The fact that all events have the same EventArgs is an indication that you might replace these events with a single event and pass the activity as a property of the HumanActivityProgressChanged and HumanActivityCompleted types.

There is no law that tells you to do so. It all depends on what you wish to expose and what clients would expect/need.


It's a question of taste, but I personally prefer the first approach. For one thing, maintenance is going to be much easier. And it is simply more efficient to code that way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜