Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Defensive GUI Programming

Today I want to talk a little bit about defensive programming for GUIs (graphical user interfaces) and other programs with
graphics callbacks.

 

Contents

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.

Use gcbo

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
the interaction.

Use Handles

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.

Reference Material

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.

Your Thoughts?

Will these ideas help you with your programs? Post here with your thoughts.

Published with MATLAB® 7.5


  • print