{"id":963,"date":"2010-08-03T13:50:43","date_gmt":"2010-08-03T12:50:43","guid":{"rendered":"http:\/\/www.minddriven.de\/?p=963"},"modified":"2010-08-04T08:24:37","modified_gmt":"2010-08-04T07:24:37","slug":"common-ui-problem","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/common-ui-problem","title":{"rendered":"A common UI problem"},"content":{"rendered":"<p>This blog post is all about a common UI-related programming problem.  Ever since my first UI-based application I&#8217;ve come across with this  problem and never found a satisfying way to resolve it (until now \ud83d\ude09 ). This first blog post is about describing the problem and my former solution approaches. In <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/latch-design-pattern\">the next blog post<\/a> I will demonstrate a more proper solution.<\/p>\n<p>The code in these two blog posts is using WinForms  and C#, but it should be easy adoptable to other UI technologies as  well.<\/p>\n<h3>Problem description<\/h3>\n<p>It&#8217;s a common problem: you  want to react on an event like the <code>TextChanged<\/code> event on a <code>TextBox<\/code>, but <strong> <em>ONLY<\/em> if the user changed<\/strong> the text and it&#8217;s not changed programmatically. For example you want to update some data, when the user changes the content of a <code>TextBox<\/code>, but this update process should not be triggered when the progam itself sets some data and therefore updates the text. The  starting point for that could be something like the following code:<\/p>\n<pre class=\"brush:csharp\">public partial class SomeControl : UserControl\r\n{\r\n    \/\/ ...\r\n\r\n    private ViewData _viewData;\r\n    public ViewData ViewData\r\n    {\r\n        get { return _viewData; }\r\n        set\r\n        {\r\n            _viewData = value;\r\n            if (value != null)\r\n            {\r\n                _someTextBox.Text = value.SomeValue;\r\n                \/\/ other operations\r\n            }\r\n        }\r\n    }\r\n\r\n    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)\r\n    {\r\n        \/\/ perform data\/view update operations\r\n    }\r\n}<\/pre>\n<p>Here the <code>OnSomeTextBoxTextChanged()<\/code> method is bound to the <code>_someTextBox.TextChanged<\/code> event. <code>ViewData<\/code> is a class with arbitrary data that should show up in the UI.<br \/>\n<strong>Notice the problem<\/strong>: when the <code>ViewData<\/code> property is set programmatically the <code>OnSomeTextBoxTextChanged()<\/code> method is being executed, which is not what was intended (firing the event only when the user changes the value of the <code>TextBox<\/code>).<\/p>\n<p>A similar problem arises with <strong>infinite loops<\/strong>. Imagine a user changes something in the UI and an event <code>X<\/code> is fired. You hook this event and start a complex UI workflow, which at the end fires the event <code>X<\/code> again. The proces is executed again and very easy you come into an infinite loop situation. If you are an UI developer you would very probably agree that UI event chains are often opaque and can get messy.<\/p>\n<p>Let&#8217;s look at some obvious, however not very elegant, solutions.<\/p>\n<h3>Approach #1: Temporary event detach<\/h3>\n<p>One of those simple solution is the <strong>temporary detachment<\/strong> of the problematic event. For example if you don&#8217;t want to react on the <code>TextChanged<\/code> event when the <code>TextBox.Text<\/code> property is set programmatically, you could detach your event handler from <code>TextChanged<\/code> before setting the <code>Text<\/code> and afterwards attach it again. This approach is shown in the following  example code:<\/p>\n<pre class=\"brush:csharp\">public partial class SomeControl : UserControl\r\n{\r\n    \/\/ ...\r\n\r\n    private ViewData _viewData;\r\n    public ViewData ViewData\r\n    {\r\n        get { return _viewData; }\r\n        set\r\n        {\r\n            _viewData = value;\r\n            if (value != null)\r\n            {\r\n                _someTextBox.TextChanged -= OnSomeTextBoxTextChanged;\r\n                _someTextBox.Text = value.SomeValue;\r\n                _someTextBox.TextChanged += OnSomeTextBoxTextChanged;\r\n\r\n                \/\/ other operations\r\n            }\r\n        }\r\n    }\r\n\r\n    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)\r\n    {\r\n        \/\/ perform data\/view update operations\r\n    }\r\n}<\/pre>\n<p>While this is working, it&#8217;s not a recommendable solution, because there are <strong>several shortcomings<\/strong>. First the manual event handling is not very intuitive and <em>doesn&#8217;t explicitly reveal the intent<\/em> of the programmer with this manual process. Thus your code is more difficult to read for others (and after some months for you as well). Moreover, you get <em>undefined states<\/em> when exceptions are thrown and caught in an outer component (and you miss a <code>finally<\/code> which attaches the event again). Then the event handler could be detached further on and the UI isn&#8217;t working properly afterwards. The whole event detach\/attach process is getting very messy if you have <em>complex views<\/em> with many such problematic events. Last but not least this manual event handling process <em>binds your code tightly<\/em> to the view and you get trouble if you want to refactor several parts out.<\/p>\n<h3>Approach #2: Boolean flags<\/h3>\n<p>A similarly simple approach comes with <em>boolean flags<\/em> which indicate that a value is currently set  programmatically and thus that <em>Changed<\/em> events should not be handled. The following code shows an example how this could solve our initial problem:<\/p>\n<pre class=\"brush:csharp\">public partial class SomeControl : UserControl\r\n{\r\n    \/\/ ...\r\n\r\n    private bool _isTextSetByProgram = false;\r\n\r\n    private ViewData _viewData;\r\n    public ViewData ViewData\r\n    {\r\n        get { return _viewData; }\r\n        set\r\n        {\r\n            _viewData = value;\r\n            if (value != null)\r\n            {\r\n                _isTextSetByProgram = true;\r\n                _someTextBox.Text = value.SomeValue;\r\n                _isTextSetByProgram = false;\r\n\r\n                \/\/ other operations\r\n            }\r\n        }\r\n    }\r\n\r\n    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)\r\n    {\r\n        if (!_isTextSetByProgram)\r\n        {\r\n            \/\/ perform data\/view update operations\r\n        }\r\n    }\r\n}<\/pre>\n<p>I think this is the <strong>most common solution<\/strong> that I&#8217;ve seen for the problem. For myself I must admit that I&#8217;ve mostly used this approach. But it has the <strong>same disadvantages<\/strong> like the event detach\/attach solution (except the tight view coupling). Boolean variables don&#8217;t explicitly show the intent behind them and get likewise messy if used in complex situations where you could have dozens of those variables scattered around a view.<\/p>\n<p>So while those solutions are very widespread and work they <strong>just don&#8217;t feel <em>right<\/em> and clean<\/strong>. But what&#8217;s the alternative? An interesting little one I will show you in <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/latch-design-pattern\">the next post<\/a> which comes shortly.<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This blog post is all about a common UI-related programming problem. Ever since my first UI-based application I&#8217;ve come across with this problem and never found a satisfying way to resolve it (until now \ud83d\ude09 ). This first blog post is about describing the problem and my former solution approaches. In the next blog post &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/common-ui-problem\" class=\"more-link\"><span class=\"screen-reader-text\">A common UI problem<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[266,181,265],"class_list":["post-963","post","type-post","status-publish","format-standard","hentry","category-design-patterns","tag-boolean-flags","tag-events","tag-ui-problem"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/963","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=963"}],"version-history":[{"count":18,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/963\/revisions"}],"predecessor-version":[{"id":979,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/963\/revisions\/979"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=963"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=963"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=963"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}