This is a perfectly reasonable question, and with a bit of care it is possible to write GUI code that is easy to maintain. Some suggestions:
Put the GUI layout code and the "business logic" in different m-files. (see this FileExchange submission for example code). Relatedly, use nested functions to maintain GUI state instead of passing of using setappdata and getappdata or passing around a structure.
In general, use nested and anonymous functions for callbacks. Nested function are similar to inner classes in Java, and anonymous functions implement lexical closures (like blocks in Ruby).
Use exceptions to deal gracefully with errors.
Give each GUI object (e.g., slider, axes) a unique and meaningful tag. For example, "frequencySlider" or "dataAxes". This helps reinforce the separation between GUI layout and the logic.
The gui controls provided by GUIDE are fairly low-level, but you can implement reusable higher-level components by choosing systematic tag names for the various controls (e.g., 'frequencySlider' for a slider and the 'frequencyLabel' for the associated text label). The component initialization routine can use findobj to look up the various parts of the component and initialize them. E.g.
function myComponent(fig, basename)
sliderHandle = findobj(fig, 'tag', [basename 'Slider']);
textHandle = findobj(fig, 'tag', [basename 'Label']);
% initialize ...
set(sliderHandle, 'Callback', @sliderCallback);
% nested function for callback; note use of sliderHandle
function sliderCallback(h,e)
fprintf('current value is %g\n, get(sliderHandle,'Value'));
end
end
- If you are using R2008a or later, there is lot of additional support for OO development: