{"id":2945,"date":"2022-12-14T03:30:50","date_gmt":"2022-12-14T08:30:50","guid":{"rendered":"https:\/\/blogs.mathworks.com\/developer\/?p=2945"},"modified":"2022-12-14T03:30:50","modified_gmt":"2022-12-14T08:30:50","slug":"the-power-of-encapsulation","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/developer\/2022\/12\/14\/the-power-of-encapsulation\/","title":{"rendered":"Han Solo Revisited"},"content":{"rendered":"<div class=\"content\"><p>A long time ago in a blog post far, far away&#8230; Andy <a href=\"https:\/\/blogs.mathworks.com\/developer\/2016\/08\/08\/han-solo-encapsulation\/\">wrote about Han Solo Encapsulation<\/a> &#8211; to keep Jabba&#8217;s &#8220;system working as designed he needed to encapsulate his system behind a rock solid interface&#8221;.<\/p><p>By a stroke of good fortune, or judicious design choices depending on your perspective, a recent refactoring job that I thought could have far reaching consequences turned into a few changes in a single class, ultimately saving much time. Let&#8217;s have a look.<\/p><p>My scenario is that I have a <tt>DataProvider<\/tt> that accepts a <tt>DataRequest<\/tt> and returns some data:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataProvider\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        \r\n        <span class=\"keyword\">function<\/span> data = getData(dataProvider,dataRequest)\r\n\r\n            <span class=\"keyword\">arguments<\/span>\r\n                dataProvider (1,1) DataProvider\r\n                dataRequest (1,1) DataRequest\r\n            <span class=\"keyword\">end<\/span>\r\n\r\n            <span class=\"comment\">% Implementation continues...<\/span>\r\n\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\r\n<p>The <tt>DataRequest<\/tt> looks like this:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataRequest\r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        Make (1,1) string = missing\r\n        Model (1,1) string = missing\r\n        ManufacturingYear (1,1) datetime = missing\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\r\n<p>It defines relevant properties that the <tt>DataProvider<\/tt> needs to serve up the data. All the values are scalar and have default values of <a href=\"https:\/\/uk.mathworks.com\/help\/matlab\/ref\/missing.html\">missing<\/a> to represent the fact that they are &#8220;unset&#8221; by the user.<\/p><p>To form its query, the <tt>DataProvider<\/tt> must extract the values of each property. To do this, it needs to know that &#8220;unset&#8221; is represented by &#8220;missing&#8221; and therefore it should be ignored from the search condition.<\/p><p>Here&#8217;s one possible implementation in <tt>DataProvider<\/tt>:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataProvider\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        \r\n        <span class=\"keyword\">function<\/span> data = getData(dataProvider,dataRequest)\r\n\r\n            <span class=\"keyword\">arguments<\/span>\r\n                dataProvider (1,1) DataProvider\r\n                dataRequest (1,1) DataRequest\r\n            <span class=\"keyword\">end<\/span>\r\n            \r\n            searchTerms = {};\r\n            propsToGet = [<span class=\"string\">\"Make\"<\/span> <span class=\"string\">\"ManufacturingYear\"<\/span> <span class=\"string\">\"Model\"<\/span>];\r\n            \r\n            <span class=\"keyword\">for<\/span> prop = propsToGet\r\n                <span class=\"keyword\">if<\/span> ~ismissing(dataRequest.(prop))\r\n                    searchTerms = [searchTerms {prop} {dataRequest.(prop)}];\r\n                <span class=\"keyword\">end<\/span>\r\n            <span class=\"keyword\">end<\/span>\r\n\r\n            result = dataProvider.search(searchTerms{:});\r\n\r\n            <span class=\"comment\">% Implementation continues...<\/span>\r\n\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\r\n<p>The problem here is that <tt>DataProvider<\/tt>, and <i>any other code<\/i> that makes use of <tt>DataRequest<\/tt>, is coupled to how <tt>DataRequest<\/tt> represents its &#8220;unset&#8221; values. That&#8217;s something that should be encapsulated within the <tt>DataRequest<\/tt>. What my <tt>DataProvider<\/tt> really wants is an array of name-value pairs of non-missing property names and values.<\/p><p>(We could also describe this as an instance of the <a href=\"https:\/\/www.martinfowler.com\/bliki\/TellDontAsk.html\"><i>tell don&#8217;t ask<\/i> principle<\/a> since we&#8217;re not actually hiding <tt>DataRequest<\/tt>&#8217;s properties from the outside world.)<\/p><p>Let&#8217;s refactor the <tt>DataRequest<\/tt> to add a method that does just that. I&#8217;ve called it <tt>namedargs2cell<\/tt> due to its similarity to the <a href=\"https:\/\/uk.mathworks.com\/help\/matlab\/ref\/namedargs2cell.html\">built-in MATLAB function<\/a>.<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataRequest\r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        Make (1,1) string = missing\r\n        Model (1,1) string = missing\r\n        ManufacturingYear (1,1) datetime = missing\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        \r\n        <span class=\"keyword\">function<\/span> paramCell = namedargs2cell(dataRequest)\r\n            \r\n            <span class=\"keyword\">arguments<\/span>\r\n                dataRequest (1,1) DataRequest\r\n            <span class=\"keyword\">end<\/span>\r\n            \r\n            paramCell = {};\r\n            propsToGet = [<span class=\"string\">\"Make\"<\/span> <span class=\"string\">\"ManufacturingYear\"<\/span> <span class=\"string\">\"Model\"<\/span>];\r\n            \r\n            <span class=\"keyword\">for<\/span> prop = propsToGet\r\n                <span class=\"keyword\">if<\/span> ~ismissing(dataRequest.(prop))\r\n                    paramCell = [paramCell {prop} {dataRequest.(prop)}];\r\n                <span class=\"keyword\">end<\/span>\r\n            <span class=\"keyword\">end<\/span>\r\n            \r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\r\n<p>This makes our <tt>DataProvider<\/tt> much simpler:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataProvider\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        \r\n        <span class=\"keyword\">function<\/span> data = getData(dataProvider,request)\r\n\r\n            <span class=\"keyword\">arguments<\/span>\r\n                dataProvider (1,1) DataProvider\r\n                request (1,1) DataRequest\r\n            <span class=\"keyword\">end<\/span>\r\n\r\n            searchTerms = namedargs2cell(request);\r\n            result = dataProvider.search(searchTerms{:});\r\n\r\n            <span class=\"comment\">% Implementation continues...<\/span>\r\n\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><p>Returning to our encapsulation principle, what do we achieve? In my real-life case, I wanted to change the <tt>DataRequest<\/tt> to allow multiple values to be specified for a given property rather than just scalars. It therefore makes sense to represent &#8220;unset&#8221; with an empty rather that with a scalar missing. Since all knowledge of how &#8220;unset&#8221; is represented is contained within the <tt>DataRequest<\/tt>, the <i>only changes<\/i> I needed to make were within <tt>DataRequest<\/tt> itself. No other code had to be touched:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DataRequest\r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        Make (1,:) string\r\n        Model (1,:) string\r\n        ManufacturingYear (1,:) datetime\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        \r\n        <span class=\"keyword\">function<\/span> paramCell = namedargs2cell(dataRequest)\r\n            \r\n            <span class=\"keyword\">arguments<\/span>\r\n                dataRequest (1,1) DataRequest\r\n            <span class=\"keyword\">end<\/span>\r\n            \r\n            paramCell = {};\r\n            propsToGet = [<span class=\"string\">\"Make\"<\/span> <span class=\"string\">\"ManufacturingYear\"<\/span> <span class=\"string\">\"Model\"<\/span>];\r\n            \r\n            <span class=\"keyword\">for<\/span> prop = propsToGet\r\n                <span class=\"keyword\">if<\/span> ~all(isempty(dataRequest.(prop)))\r\n                    paramCell = [paramCell {prop} {dataRequest.(prop)}];\r\n                <span class=\"keyword\">end<\/span>\r\n            <span class=\"keyword\">end<\/span>\r\n            \r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\r\n<p>In the above, note how <tt>ismissing<\/tt> has become <tt>all(isempty(&#8230;))<\/tt>.<\/p><p>In conclusion, by providing the right interface to your classes, code changes can become much more limited in scope and easier to implement.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_274c3903a6ce4454b450951ca46008df() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='274c3903a6ce4454b450951ca46008df ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 274c3903a6ce4454b450951ca46008df';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2022 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_274c3903a6ce4454b450951ca46008df()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2022b<br><\/p><\/div><!--\r\n274c3903a6ce4454b450951ca46008df ##### SOURCE BEGIN #####\r\n%% Han Solo revisited\r\n% A long time ago in a blog post far, far away\u2026 Andy <https:\/\/blogs.mathworks.com\/developer\/2016\/08\/08\/han-solo-encapsulation\/ \r\n% wrote about Han Solo Encapsulation> \u2013 to keep Jabba\u2019s \u201csystem working as designed \r\n% he needed to encapsulate his system behind a rock solid interface\u201d. \r\n% \r\n% By a stroke of good fortune, or judicious design choices depending on your \r\n% perspective, a recent refactoring job that I thought could have far reaching \r\n% consequences turned into a few changes in a single class, ultimately saving \r\n% much time. Let\u2019s have a look. \r\n% \r\n% My scenario is that I have a |DataProvider| that accepts a |DataRequest| and \r\n% returns some data:\r\n% \r\n% <include>DataProviderInit.m<\/include>\r\n% \r\n% The |DataRequest| looks like this:\r\n% \r\n% <include>DataRequestInit.m<\/include>\r\n% \r\n% It defines relevant properties that the |DataProvider| needs to serve up the \r\n% data. All the values are scalar and have default values of <https:\/\/uk.mathworks.com\/help\/matlab\/ref\/missing.html \r\n% missing> to represent the fact that they are \u201cunset\u201d by the user.\r\n% \r\n% To form its query, the |DataProvider| must extract the values of each property. \r\n% To do this, it needs to know that \u201cunset\u201d is represented by \u201cmissing\u201d and therefore \r\n% it should be ignored from the search condition. \r\n% \r\n% Here\u2019s one possible implementation in |DataProvider|:\r\n% \r\n% <include>DataProvider.m<\/include>\r\n% \r\n% The problem here is that |DataProvider|, and _any other code_ that makes use \r\n% of |DataRequest|, is coupled to how |DataRequest| represents its \u201cunset\u201d values. \r\n% That\u2019s something that should be encapsulated within the |DataRequest|. What \r\n% my |DataProvider| really wants is an array of name-value pairs of non-missing \r\n% property names and values.\r\n% \r\n% (We could also describe this as an instance of the <https:\/\/www.martinfowler.com\/bliki\/TellDontAsk.html \r\n% _tell don\u2019t ask_ principle> since we\u2019re not actually hiding |DataRequest|\u2019s \r\n% properties from the outside world.)\r\n% \r\n% Let\u2019s refactor the |DataRequest| to add a method that does just that. I\u2019ve \r\n% called it |namedargs2cell| due to its similarity to the <https:\/\/uk.mathworks.com\/help\/matlab\/ref\/namedargs2cell.html \r\n% built-in MATLAB function>.\r\n% \r\n% <include>DataRequest.m<\/include>\r\n% \r\n% This makes our |DataProvider| much simpler:\r\n% \r\n% <include>DataProvider2.m<\/include>\r\n% \r\n% Returning to our encapsulation principle, what do we achieve? In my real-life \r\n% case, I wanted to change the |DataRequest| to allow multiple values to be specified \r\n% for a given property rather than just scalars. It therefore makes sense to represent \r\n% \u201cunset\u201d with an empty rather that with a scalar missing. Since all knowledge \r\n% of how \u201cunset\u201d is represented is contained within the |DataRequest|, the _only \r\n% changes_ I needed to make were within |DataRequest| itself. No other code had \r\n% to be touched:\r\n% \r\n% <include>DataRequest2.m<\/include>\r\n% \r\n% In the above, note how |ismissing| has become |all(isempty(\u2026))|.\r\n% \r\n% In conclusion, by providing the right interface to your classes, code changes \r\n% can become much more limited in scope and easier to implement.\r\n##### SOURCE END ##### 274c3903a6ce4454b450951ca46008df\r\n-->","protected":false},"excerpt":{"rendered":"<p>A long time ago in a blog post far, far away&#8230; Andy wrote about Han Solo Encapsulation &#8211; to keep Jabba&#8217;s &#8220;system working as designed he needed to encapsulate his system behind... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/developer\/2022\/12\/14\/the-power-of-encapsulation\/\">read more >><\/a><\/p>","protected":false},"author":178,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/2945"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/users\/178"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/comments?post=2945"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/2945\/revisions"}],"predecessor-version":[{"id":2954,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/2945\/revisions\/2954"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/media?parent=2945"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/categories?post=2945"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/tags?post=2945"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}