Defensive GUI Programming
Today I want to talk a little bit about defensive programming for GUIs (graphical user interfaces) and other programs with
What Can Go Wrong
First, why is this worthy of a blog at all? Well, supposed the following. Someone, who shall remain nameless, has created
a GUI to do a very useful task. However, the interactions are programmed to work on the current figure or current axes.
Now, a user of this GUI, who shall also remain nameless, is a very impatient person and, while waiting for the GUI to respond,
starts working in another figure window. When this user goes back to the GUI and tries to accomplish the next task, strange
behaviors and errors emerge. What's gone wrong? Most likely, the GUI callbacks, which implement the behavior of the GUI,
probably are programmed using a poor technique.
Don't Depend on gca, gcf
One technique that can easily misfire is referring to some entity that has global state, such as gcf or gca, referring to the current figure or axes. The problem arises when a GUI user interrupts the interaction in a GUI with interaction
in another figure window. By the time the user returns to the initial GUI, either or both of gcf or gca may no longer refer to the objects intended by the GUI author. What should the GUI programmer do instead? There are several
acceptable choices available.
One possibility is to have the callback refer to gcbo, the handle of the object from which the callback is executed. From there, you can find other objects needed to complete
An even better choice is store handles to the objects you want to the GUI to operate on, either in the workspace available
to a nested function, or in a structure tucked inside the GUI, perhaps in application data, accessed through getappdata and the corresponding set method.
Here are some references in the MATLAB documentation to help you with programming a GUI.
Avoid Global State
Global state is fragile and can be easy to disrupt. To avoid using global state, use techniques like the ones in this blog,
the recent one on using the MException object, or use nested functions, among other possibilities.
Will these ideas help you with your programs? Post here with your thoughts.
Published with MATLAB® 7.5
要发表评论，请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。