Why is it bad practice to call an eventhandler fro

2019-01-21 12:10发布

Say you have a menu item and a button that do the same task. Why is it bad practice to put the code for the task into one control's action event and then make a call to that event from the other control? Delphi allows this as does vb6 but realbasic doesn't and says you should put the code into a method that is then called by both the menu and the button

9条回答
手持菜刀,她持情操
2楼-- · 2019-01-21 12:35

Because you should separate internal logic to some other function and call this function...

  1. from both event handlers
  2. separately from code if you need to

This is a more elegant solution and is much easier to maintain.

查看更多
Melony?
3楼-- · 2019-01-21 12:36

Suppose at some point you decide that the menu item no longer makes sense, and you want to get rid of the menu item. If you just have one other control pointing to the menu item's event handler, that might not be a big problem, you can just copy the code into the button's event handler. But if you have several different ways the code can be invoked, you'll have to do a lot of changing.

Personally I like the way Qt handles this. There is a QAction class with it's own event handler that can be hooked, and then the QAction is associated with any UI elements that need to perform that task.

查看更多
【Aperson】
4楼-- · 2019-01-21 12:39

Another big reason is for testability. When event handling code is buried in the UI, the only way to test this is via either manual testing or automated testing that is heavily tied to the UI. (e.g. Open menu A, Click button B). Any change in the UI naturally can then break dozens of tests.

If the code is refactored into a module that deals exclusively with the job it needs to perform, then testing become a whole lot easier.

查看更多
Lonely孤独者°
5楼-- · 2019-01-21 12:43

Separation of concerns. A private event for a class should be encapsulated within that class and not called from external classes. This makes your project easier to change down the road if you have strong interfaces between objects and minimize the occurences of multiple entry points.

查看更多
Melony?
6楼-- · 2019-01-21 12:44

Suppose at some time you decided that the menu should do something slightly differently. Perhaps this new change only happens under some specific circumstances. You forget about the button, but now you have changed its behaviour as well.

On the other hand if you call a function, you are less likely to change what it does, since you (or the next guy) knows that this will have bad consequences.

查看更多
Luminary・发光体
7楼-- · 2019-01-21 12:47

Why is it bad practice? Because it is much easier to reuse code when it is not embedded into UI controls.

Why can't you do it in REALbasic? I doubt there's any technical reason; it's likely just a design decision they made. It certainly does enforce better coding practices.

查看更多
登录 后发表回答