{"id":114,"date":"2007-11-07T16:38:40","date_gmt":"2007-11-07T21:38:40","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/11\/07\/defensive-gui-programming\/"},"modified":"2016-08-02T13:08:12","modified_gmt":"2016-08-02T18:08:12","slug":"defensive-gui-programming","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/11\/07\/defensive-gui-programming\/","title":{"rendered":"Defensive GUI Programming"},"content":{"rendered":"<div class=\"content\">\n<p>Today I want to talk a little bit about defensive programming for GUIs (graphical user interfaces) and other programs with<br \/>\ngraphics callbacks.<\/p>\n<p>&nbsp;<\/p>\n<h3>Contents<\/h3>\n<div>\n<ul>\n<li><a href=\"#1\">What Can Go Wrong<\/a><\/li>\n<li><a href=\"#2\">Don't Depend on gca, gcf<\/a><\/li>\n<li><a href=\"#3\">Use gcbo<\/a><\/li>\n<li><a href=\"#4\">Use Handles<\/a><\/li>\n<li><a href=\"#5\">Reference Material<\/a><\/li>\n<li><a href=\"#6\">Avoid Global State<\/a><\/li>\n<li><a href=\"#7\">Your Thoughts?<\/a><\/li>\n<\/ul>\n<\/div>\n<h3>What Can Go Wrong<a name=\"1\"><\/a><\/h3>\n<p>First, why is this worthy of a blog at all? Well, supposed the following. Someone, who shall remain nameless, has created<br \/>\na GUI to do a very useful task. However, the interactions are programmed to work on the current figure or current axes.<br \/>\nNow, a user of this GUI, who shall also remain nameless, is a very impatient person and, while waiting for the GUI to respond,<br \/>\nstarts working in another figure window. When this user goes back to the GUI and tries to accomplish the next task, strange<br \/>\nbehaviors and errors emerge. What's gone wrong? Most likely, the GUI callbacks, which implement the behavior of the GUI,<br \/>\nprobably are programmed using a poor technique.<\/p>\n<h3>Don't Depend on gca, gcf<a name=\"2\"><\/a><\/h3>\n<p>One technique that can easily misfire is referring to some entity that has global state, such as <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/gcf.html\"><tt>gcf<\/tt><\/a> or <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/gca.html\"><tt>gca<\/tt><\/a>, referring to the current figure or axes. The problem arises when a GUI user interrupts the interaction in a GUI with interaction<br \/>\nin another figure window. By the time the user returns to the initial GUI, either or both of <tt>gcf<\/tt> or <tt>gca<\/tt> may no longer refer to the objects intended by the GUI author. What should the GUI programmer do instead? There are several<br \/>\nacceptable choices available.<\/p>\n<h3>Use gcbo<a name=\"3\"><\/a><\/h3>\n<p>One possibility is to have the callback refer to <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/gcbo.html\"><tt>gcbo<\/tt><\/a>, the handle of the object from which the callback is executed. From there, you can find other objects needed to complete<br \/>\nthe interaction.<\/p>\n<h3>Use Handles<a name=\"4\"><\/a><\/h3>\n<p>An even better choice is store handles to the objects you want to the GUI to operate on, either in the workspace available<br \/>\nto a nested function, or in a structure tucked inside the GUI, perhaps in application data, accessed through <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/getappdata.html\"><tt>getappdata<\/tt><\/a> and the corresponding set method.<\/p>\n<h3>Reference Material<a name=\"5\"><\/a><\/h3>\n<p>Here are some references in the MATLAB documentation to help you with programming a GUI.<\/p>\n<div>\n<ul>\n<li><a title=\"https:\/\/www.mathworks.com\/help\/matlab\/creating_guis\/about-the-simple-programmatic-gui-example.html (link no longer works)\">Creating GUIs Programmatically<\/a><\/li>\n<li><a title=\"https:\/\/www.mathworks.com\/help\/matlab\/creating_guis\/about-the-simple-guide-gui-example.html (link no longer works)\">Creating GUIs with GUIDE<\/a><\/li>\n<\/ul>\n<\/div>\n<h3>Avoid Global State<a name=\"6\"><\/a><\/h3>\n<p>Global state is fragile and can be easy to disrupt. To avoid using global state, use techniques like the ones in this blog,<br \/>\nthe recent one on using the <tt>MException<\/tt> object, or use nested functions, among other possibilities.<\/p>\n<h3>Your Thoughts?<a name=\"7\"><\/a><\/h3>\n<p>Will these ideas help you with your programs? Post <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=114#respond\">here<\/a> with your thoughts.<\/p>\n<p><script>\/\/ <![CDATA[\nfunction grabCode_c0e6b599a7e348e59abeb0cf4144fb2a() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='c0e6b599a7e348e59abeb0cf4144fb2a ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' c0e6b599a7e348e59abeb0cf4144fb2a';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Loren Shure';\n        copyright = 'Copyright 2007 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n\n\n\n\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\n\n\n\n\n\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }\n\/\/ ]]><\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\"><a><span style=\"font-size: x-small; font-style: italic;\">Get<br \/>\nthe MATLAB code<br \/>\n<noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>Published with MATLAB\u00ae 7.5<\/p>\n<\/div>\n<p><!--\nc0e6b599a7e348e59abeb0cf4144fb2a ##### SOURCE BEGIN #####\n%% Defensive GUI Programming\n% Today I want to talk a little bit about defensive programming for GUIs\n% (graphical user interfaces) and other programs with graphics callbacks.\n%% What Can Go Wrong\n% First, why is this worthy of a blog at all?  Well, supposed the\n% following.  Someone, who shall remain nameless, has created a GUI to do a\n% very useful task.  However, the interactions are programmed to work on\n% the current figure or current axes.  Now, a user of this GUI, who shall\n% also remain nameless, is a very impatient person and, while waiting for\n% the GUI to respond, starts working in another figure window.  When this\n% user goes back to the GUI and tries to accomplish the next task, strange\n% behaviors and errors emerge.  What's gone wrong?  Most likely, the GUI\n% callbacks, which implement the behavior of the GUI, probably are\n% programmed using a poor technique.\n%% Don't Depend on gca, gcf\n% One technique that can easily misfire is referring to some entity that\n% has global state, such as\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/gcf.html |gcf|>\n% or  <https:\/\/www.mathworks.com\/help\/matlab\/ref\/gca.html |gca|>,\n% referring to the current figure or axes.  The problem arises when a GUI\n% user interrupts the interaction in a GUI with interaction in another\n% figure window.  By the time the user returns to the initial GUI, either\n% or both of |gcf| or |gca| may no longer refer to the objects intended by\n% the GUI author.  What should the GUI programmer do instead?  There are\n% several acceptable choices available.\n%% Use gcbo\n% One possibility is to have the callback refer to\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/gcbo.html |gcbo|>,\n% the handle of the object from which the callback is executed.  From\n% there, you can find other objects needed to complete the interaction.\n%% Use Handles\n% An even better choice is store handles to the objects you want to the GUI\n% to operate on, either in the workspace available to a nested function, or\n% in a structure tucked inside the GUI, perhaps in application data,\n% accessed through\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/getappdata.html |getappdata|>\n% and the corresponding set method.\n%% Reference Material\n% Here are some references in the MATLAB documentation to help you with\n% programming a GUI.\n%\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/creating_guis\/bqz6qcd.html Creating GUIs Programmatically>\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/creating_guis\/bqz6p81.html Creating GUIs with GUIDE>\n%\n%% Avoid Global State\n% Global state is fragile and can be easy to disrupt.  To avoid using\n% global state, use techniques like the ones in this blog, the recent one\n% on using the |MException| object, or use nested functions, among other\n% possibilities.\n%% Your Thoughts?\n% Will these ideas help you with your programs?  Post\n% <https:\/\/blogs.mathworks.com\/loren\/?p=114#respond here> with your\n% thoughts.\n\n##### SOURCE END ##### c0e6b599a7e348e59abeb0cf4144fb2a\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\nToday I want to talk a little bit about defensive programming for GUIs (graphical user interfaces) and other programs with<br \/>\ngraphics callbacks.<br \/>\n&nbsp;<br \/>\nContents<\/p>\n<p>What Can Go Wrong<br \/>\nDon't Depend on... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/11\/07\/defensive-gui-programming\/\">read more >><\/a><\/p>\n","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,14],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/114"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=114"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/114\/revisions"}],"predecessor-version":[{"id":1887,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/114\/revisions\/1887"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=114"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=114"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=114"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}