将事件处理代码放入自己的方法中,这是一个好的设计吗?
时间:2020-03-06 14:58:22 来源:igfitidea点击:
在Windows窗体上为按钮成像,该按钮在被单击时会执行某些操作。
引发的点击事件通常绑定到诸如
protected void Button1_Click(object sender, EventArgs e) { }
我有时在其他人的代码中看到的是,按钮行为的实现未放入Button1_Click方法中,而是放入了自己的方法中,如下所示:
private DoStuff() { } protected void Button1_Click(object sender, EventArgs e) { this.DoStuff(); }
尽管我在这里看到了优势(例如,如果这段代码在其他内部需要使用,则可以轻松使用),但我想知道,这是否是一个好的设计决定?
所以问题是:
将事件处理代码放入自己的方法中通常是一个好主意吗?如果是,那么这些方法的命名约定被证明是最佳实践?
解决方案
一个好的经验法则是查看该方法是否正在执行某些特定于UI的操作,或者实际上是在执行通用操作。例如,臀部单击方法可以处理单击或者提交表单。如果是前一种,可以将其保留在button_click处理程序中,但后者应使用自己的方法。我要说的是,牢记单一责任原则。
如果发生以下情况,我将事件处理代码放入单独的方法中:
- 该代码将被多个事件或者其他任何地方调用,或者
- 该代码实际上与GUI无关,而更像是后端工作。
所有小的且仅与GUI相关的事物都始终进入处理程序,有时即使是从同一事件中调用它(只要签名相同)也是如此。因此,更像是,如果它是常规操作,则使用单独的方法,如果该方法与实际事件密切相关,则不要使用。
直接的答案是肯定的。最好将任务封装到自己的方法中,不仅可以在其他地方重用,而且从OOP的角度来看,这样做是有意义的。在这种特殊情况下,单击按钮将启动一个过程调用DoStuff。该按钮仅触发该过程。 Button1_Click是与DoStuff完全独立的任务。但是,DoStuff不仅更具描述性,而且还使按钮与实际完成的工作脱钩。
A good rule of thumb is to see whether the method is doing sometihng UI specific, or actually implementing a generic action. For example a buttock click method could either handle a click or submit a form. If its the former kind, its ok to leave it in the button_click handler, but the latter deserves a method of its own. All I'm saying is, keep the single responsibility principle in mind. I put the event handling code into a separate method if: The code is to be called by multiple events or from anywhere else or The code does not actually have to do with the GUI and is more like back-end work. Everything small and only GUI-related goes always into the handler, sometimes even if it is being called from the same event (as long as the signature is the same). So it's more like, use a separate method if it is a general action, and don't if the method is closely related to the actual event.
在这种情况下,我将保留DoStuff()方法,但使用以下方法进行订阅:
button1.Click += delegate { DoStuff(); }
诚然,这不会令那些在设计人员中进行所有活动布线的人感到高兴……但我发现亲自检查起来更简单。 (我也讨厌自动生成的事件处理程序名称...)