Is it bad practice to write inline event handlers

柔情痞子 提交于 2019-12-03 00:53:37

It's absolutely fine - although there are two caveats:

  • If you're modifying a local variable from within a closure, you should make sure you understand what you're doing.
  • You won't be able to unsubscribe from the event

Typically I only inline really simple event handlers - for anything more involved, I use lambda expressions (or anonymous methods) to subscribe with a call to an method with a more appropriate method:

// We don't care about the arguments here; SaveDocument shouldn't need parameters
saveButton.Click += delegate { SaveDocument(); };

In most cases I would rather have the separate methods like “timer_Tick()”, however I should rather it be called OnTimerTick() as:

  • When I read the class, it is clearer wheat is going on. The “On” tells me its can event handler.
  • It is easier to set a break point in the method in the “inline” case.
  • The event is fired a long time after “Foo” contractor has returned, and I don’t think it as running in t the scope of the contractor.

However if the event will only be fired before the method it is declared in-line returns and the object the event is set on has a scope what that is limited to the declaring method, then I think the “in line” version is better. Hence I like using “in line” for the compare delegate being passed to a “sort” method.

You put the two samples together. It is clear that the second option (which you don't prefer) is the most readable.

Code readability and maintainability are very important. Keep things simple, as easy as possible to understand. Lambda expressions are generally considered harder to understand by majority of people. Even if they are a second nature for you for others might not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!