{"id":1190,"date":"2017-12-22T17:53:00","date_gmt":"2017-12-22T22:53:00","guid":{"rendered":"https:\/\/blogs.mathworks.com\/developer\/?p=1190"},"modified":"2017-12-26T10:59:50","modified_gmt":"2017-12-26T15:59:50","slug":"property-validation","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/developer\/2017\/12\/22\/property-validation\/","title":{"rendered":"The Gift of Property Cheer"},"content":{"rendered":"<div class=\"content\"><p>Well, it's that time of year, Christmas, Hanukkah, Kwanzaa, Ramadan, Winter Solstice, or you know.......Friday. You deserve the gift of a blog post. Here's a nugget of object oriented goodness in MATLAB, what better gift could there be?<\/p><p>Well perhaps a quick follow up discussion on some more benefits of MATLAB object properties as we have discussed a <a href=\"https:\/\/blogs.mathworks.com\/developer\/2017\/04\/04\/properties-of-properties\/\">couple<\/a> <a href=\"https:\/\/blogs.mathworks.com\/developer\/2016\/08\/08\/han-solo-encapsulation\/\">times<\/a> before. This time I'd like to focus on an awesome (and relatively new) feature that allows for much more streamlined validation of properties.<\/p><p>First, a quick reminder, take a look at this special string class called <tt>FancyString<\/tt> that enables decorating individual elements it the string array with additional information such as hyperlinking or bolding. This starts with the <tt>FancyString<\/tt> itself:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> FancyString \r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        PlainValue\r\n        \r\n        <span class=\"comment\">% Each element uses the \"do nothing\" decorator by default<\/span>\r\n        Decorator = DefaultDecorator; \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">properties<\/span>(Dependent)\r\n        DecoratedValue\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> fancyString = FancyString(varargin)\r\n            <span class=\"keyword\">if<\/span> nargin &lt; 1\r\n                <span class=\"keyword\">return<\/span>\r\n            <span class=\"keyword\">end<\/span>\r\n                        \r\n            plainValue = string(varargin{:});\r\n            fancyString(numel(plainValue)) = FancyString;\r\n\r\n            plainValueCell = num2cell(plainValue);\r\n            [fancyString.PlainValue] = plainValueCell{:};\r\n        <span class=\"keyword\">end<\/span>\r\n\r\n        <span class=\"keyword\">function<\/span> decorated = get.DecoratedValue(fancyString)\r\n            <span class=\"comment\">% The decorated value returns whatever the decorator adds to<\/span>\r\n            <span class=\"comment\">% the plain string.<\/span>\r\n            decorated = fancyString.Decorator.decorate(fancyString.PlainValue);\r\n        <span class=\"keyword\">end<\/span>\r\n        <span class=\"keyword\">function<\/span> s = string(fancyString)\r\n            s = reshape([fancyString.PlainValue], size(fancyString));\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><p>As well as a couple decorators to add some fanciness:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> DefaultDecorator\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> decoratedString = decorate(~, undecoratedString)\r\n            decoratedString =  undecoratedString;\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\r\n\r\n<span class=\"keyword\">classdef<\/span> HyperlinkDecorator\r\n   \r\n    <span class=\"keyword\">properties<\/span>\r\n        LinkTarget\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> decorator = HyperlinkDecorator(linkTarget)\r\n            decorator.LinkTarget = linkTarget;\r\n        <span class=\"keyword\">end<\/span>\r\n        <span class=\"keyword\">function<\/span> decoratedString = decorate(decorator, undecoratedString)\r\n            decoratedString = <span class=\"string\">\"&lt;a href=\"\"\"<\/span> + decorator.LinkTarget + <span class=\"string\">\"\"\"&gt;\"<\/span> + undecoratedString + <span class=\"string\">\"&lt;\/a&gt;\"<\/span>;\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>       \r\n    \r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n\r\n\r\n<span class=\"keyword\">classdef<\/span> BoldDecorator\r\n      \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> decoratedString = decorate(~, undecoratedString)\r\n            decoratedString = <span class=\"string\">\"&lt;strong&gt;\"<\/span> + undecoratedString + <span class=\"string\">\"&lt;\/strong&gt;\"<\/span>;\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>       \r\n    \r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><p>Now we can have a nice message with some bolding and hyperlinking holiday cheer:<\/p><pre class=\"codeinput\">holidayMessage = [<span class=\"string\">\"Happy\"<\/span> <span class=\"string\">\"Holidays\"<\/span> <span class=\"string\">\"!\"<\/span>];\r\n\r\ngreeting = FancyString(holidayMessage);\r\ngreeting(1).Decorator = BoldDecorator;\r\n\r\n<span class=\"comment\">% Add a link to US Holidays<\/span>\r\nholidayWikipediaSite = <span class=\"string\">'https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December'<\/span>;\r\ngreeting(2).Decorator = HyperlinkDecorator(holidayWikipediaSite);\r\n\r\njoin([greeting.DecoratedValue])\r\n<\/pre><pre class=\"codeoutput\">\r\nans = \r\n\r\n    \"<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Holidays<\/a> !\"\r\n\r\n<\/pre><p>Alright this is great, but there is a problem. Let's say we have an enumeration containing the different holidays and we'd like to put together a few different sets of greetings for our friends and neighbors with different preferences. Maybe this looks something like this:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> Holidays\r\n    <span class=\"comment\">% Simple (and incomplete) enumeration of some winter holidays<\/span>\r\n    \r\n    <span class=\"keyword\">enumeration<\/span>\r\n        Christmas\r\n        Hanukkah\r\n        Kwanzaa\r\n        Ramadan\r\n        WinterSolstice\r\n        NewYears\r\n    <span class=\"keyword\">end<\/span>\r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><p>That looks so nice I might just want to replace my string with one of these enumeration values. Seems reasonable.<\/p><pre class=\"codeinput\">greeting(2).PlainValue = Holidays.Kwanzaa\r\n<\/pre><pre class=\"codeoutput\">\r\ngreeting = \r\n\r\n  1&times;3 FancyString array with properties:\r\n\r\n    PlainValue\r\n    Decorator\r\n    DecoratedValue\r\n\r\n<\/pre><p>So far so good. Quick spot check?<\/p><pre class=\"codeinput\">greeting.PlainValue\r\n<\/pre><pre class=\"codeoutput\">\r\nans = \r\n\r\n    \"Happy\"\r\n\r\n\r\nans = \r\n\r\n    Kwanzaa\r\n\r\n\r\nans = \r\n\r\n    \"!\"\r\n\r\n<\/pre><p>Still looks good at first glance. Alright how about the <tt>DecoratedValue<\/tt>? Do the hyperlinking and bold operations still work? (hint: the <tt>try-catch<\/tt> I've added in the script I am using to publish this blog is a hint that something fishy might be going on):<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    greeting.DecoratedValue\r\n<span class=\"keyword\">catch<\/span> e\r\n    disp(<span class=\"string\">'Errored!'<\/span>);\r\n    disp(e.getReport(<span class=\"string\">'basic'<\/span>));\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Errored!\r\nUndefined function 'plus' for input arguments of type 'Holidays'.\r\n<\/pre><p>Alright this doesn't work because I've assigned to the <tt>PlainValue<\/tt> a value from our enumeration, but the <tt>FancyString<\/tt> (and the decorators) are expecting the value to be a string.<\/p><p>In fact, we could have supplied any arbitrary value to the property and we likely wouldn't have noticed until much farther down the line. For example, let's add a structure, which is meaningless in this context:<\/p><pre class=\"codeinput\">meaninglessStruct.SomeField = 5;\r\nmeaninglessStruct.AnotherField = true;\r\n\r\ngreeting(2).PlainValue = meaninglessStruct; <span class=\"comment\">% Assignment works!!<\/span>\r\ngreeting.PlainValue <span class=\"comment\">% Still doesn't error!<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nans = \r\n\r\n    \"Happy\"\r\n\r\n\r\nans = \r\n\r\n  struct with fields:\r\n\r\n       SomeField: 5\r\n    AnotherField: 1\r\n\r\n\r\nans = \r\n\r\n    \"!\"\r\n\r\n<\/pre><p>It only errors when we use it farther down the line, such as in concatenation:<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    [greeting.PlainValue]\r\n<span class=\"keyword\">catch<\/span> e\r\n    disp(<span class=\"string\">'Errored!'<\/span>);\r\n    disp(e.getReport(<span class=\"string\">'basic'<\/span>));\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Errored!\r\nError using string\r\nConversion to string from struct is not possible.\r\n<\/pre><p>This is clearly not optimal. Property validation to the rescue! We can make the simplest of tweaks to the <tt>FancyString<\/tt> so that we can always know for sure that the <tt>PlainValue<\/tt> property will always be a string. It's as easy as this slightly more fancy string implementation:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> MoreFancyString \r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        \r\n        <span class=\"comment\">% Property validation for the win! Let's guarantee the PlainValue<\/span>\r\n        <span class=\"comment\">% is always a string<\/span>\r\n        PlainValue (1,1) string\r\n        \r\n        Decorator = DefaultDecorator; \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">properties<\/span>(Dependent)\r\n        DecoratedValue\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> fancyString = MoreFancyString(varargin)\r\n            <span class=\"keyword\">if<\/span> nargin &lt; 1\r\n                <span class=\"keyword\">return<\/span>\r\n            <span class=\"keyword\">end<\/span>\r\n                        \r\n            plainValue = string(varargin{:});\r\n            fancyString(numel(plainValue)) = MoreFancyString;\r\n\r\n            plainValueCell = num2cell(plainValue);\r\n            [fancyString.PlainValue] = plainValueCell{:};\r\n        <span class=\"keyword\">end<\/span>\r\n\r\n        <span class=\"keyword\">function<\/span> decorated = get.DecoratedValue(fancyString)\r\n            <span class=\"comment\">% The decorated value returns whatever the decorator adds to<\/span>\r\n            <span class=\"comment\">% the plain string.<\/span>\r\n            decorated = fancyString.Decorator.decorate(fancyString.PlainValue);\r\n        <span class=\"keyword\">end<\/span>\r\n        <span class=\"keyword\">function<\/span> s = string(fancyString)\r\n            s = reshape([fancyString.PlainValue], size(fancyString));\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><p>The only difference here is in the property block where plain value was defined:<\/p><p><tt>PlainValue (1,1) string<\/tt><\/p><p>This states that the <tt>PlainValue<\/tt> must always be a scalar string, which gives us much more peace of mind as we process that code. How does it work now?<\/p><pre class=\"codeinput\">greeting = MoreFancyString(holidayMessage);\r\ngreeting(1).Decorator = BoldDecorator;\r\ngreeting(2).Decorator = HyperlinkDecorator(holidayWikipediaSite);\r\ngreeting(2).PlainValue = Holidays.Kwanzaa\r\n<\/pre><pre class=\"codeoutput\">\r\ngreeting = \r\n\r\n  1&times;3 MoreFancyString array with properties:\r\n\r\n    PlainValue\r\n    Decorator\r\n    DecoratedValue\r\n\r\n<\/pre><p>This time if you look closely you will see the enum was converted to a string<\/p><pre class=\"codeinput\">greeting(2).PlainValue\r\n<\/pre><pre class=\"codeoutput\">\r\nans = \r\n\r\n    \"Kwanzaa\"\r\n\r\n<\/pre><p>...and because of that everything else like concatenation and the string decoration works as expected:<\/p><pre class=\"codeinput\">join([greeting.PlainValue])\r\n\r\njoin([greeting.DecoratedValue])\r\n<\/pre><pre class=\"codeoutput\">\r\nans = \r\n\r\n    \"Happy Kwanzaa !\"\r\n\r\n\r\nans = \r\n\r\n    \"<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Kwanzaa<\/a> !\"\r\n\r\n<\/pre><p>It also correctly errors right away with bunk values that don't know how to be represented as strings:<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    greeting(2).PlainValue = meaninglessStruct;\r\n<span class=\"keyword\">catch<\/span> e\r\n    disp(<span class=\"string\">'Errored!'<\/span>);\r\n    disp(e.getReport(<span class=\"string\">'basic'<\/span>));\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Errored!\r\nError using y2017PropertyTypes (line 138)\r\nError setting property 'PlainValue' of class 'MoreFancyString':\r\nInvalid data type. Value must be string or be convertible to string.\r\n<\/pre><p>Awesome! A couple concluding thoughts:<\/p><div><ol><li>We could have also given this guarantee by implementing a <tt>set.PlainValue<\/tt> method that validates the input using the <tt>validateattributes<\/tt> or otherwise. This would be certainly possible, and a benefit of encapsulated properties. However, if this validation is all that is needed property validators are much more convenient and accessible.<\/li><li>Classes that are convertible to the datatype specified (in this case <tt>string<\/tt>) are automatically converted. In this case the enumeration really knows how to be interpreted correctly as a string, and so it just intuitively worked out of the box!<\/li><li>This conversion has a flipside. What this really provides is a guarantee that the actual stored value will be a <tt>string<\/tt>. However,you can set non-string values to this property as long as they are convertible to a string, and the conversion will be performed upon setting the property. This is typically the right behavior, since the value with a type conversion is the class that should be able to decide that it can be interpeted as a string. However, if you find that you wish to disallow any datatype from being assigned to the property unless it is the precise type to start with, then you may need to leverage the setter method instead to enforce that restriction directly.<\/li><\/ol><\/div><p>Have you used the new property validation features? I hope so. Actually there is much more richness to property validation than I've shown here, check out the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/validate-property-values.html\">documentation<\/a>. I've hinted at size\/shape validation but there is also the ability to pass validation functons to the value being set, as well as a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/property-validator-functions.html\">rich library of validation functions<\/a> in MATLAB for your benefit. Let us know what you think!....oh, and<\/p><pre class=\"codeinput\">holidays = enumeration(<span class=\"string\">'Holidays'<\/span>);\r\n<span class=\"keyword\">for<\/span> idx = 1:numel(holidays)\r\n    greeting(2).PlainValue = holidays(idx);\r\n    <span class=\"keyword\">if<\/span> strcmp(holidays(idx), <span class=\"string\">'Christmas'<\/span>) <span class=\"comment\">% There's always a special case<\/span>\r\n        specialGreeting = greeting;\r\n        specialGreeting(1).PlainValue = <span class=\"string\">\"Merry\"<\/span>;\r\n        disp(join([specialGreeting.DecoratedValue]));\r\n        <span class=\"keyword\">continue<\/span>;\r\n    <span class=\"keyword\">end<\/span>\r\n    disp(join([greeting.DecoratedValue]));\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\n\r\n<strong>Merry<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Christmas<\/a> !\r\n<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Hanukkah<\/a> !\r\n<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Kwanzaa<\/a> !\r\n<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">Ramadan<\/a> !\r\n<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">WinterSolstice<\/a> !\r\n<strong>Happy<\/strong> <a href=\"https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December\">NewYears<\/a> !\r\n<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/developer\/files\/y2017HolidayCheer.png\" alt=\"\"> <\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_f9ef04c1f95344fea2a79134b96a75c6() {\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='f9ef04c1f95344fea2a79134b96a75c6 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' f9ef04c1f95344fea2a79134b96a75c6';\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 2017 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_f9ef04c1f95344fea2a79134b96a75c6()\"><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; R2017b<br><\/p><\/div><!--\r\nf9ef04c1f95344fea2a79134b96a75c6 ##### SOURCE BEGIN #####\r\n%% \r\n% \r\n% Well, it's that time of year, Christmas, Hanukkah, Kwanzaa, Ramadan,\r\n% Winter Solstice, or you know.......Friday. You deserve the gift of a blog\r\n% post. Here's a nugget of object oriented goodness in MATLAB, what better\r\n% gift could there be?\r\n%\r\n% Well perhaps a quick follow up discussion on some more benefits of MATLAB\r\n% object properties as we have discussed a\r\n% <https:\/\/blogs.mathworks.com\/developer\/2017\/04\/04\/properties-of-properties\/\r\n% couple>\r\n% <https:\/\/blogs.mathworks.com\/developer\/2016\/08\/08\/han-solo-encapsulation\/\r\n% times> before. This time I'd like to focus on an awesome (and relatively\r\n% new) feature that allows for much more streamlined validation of\r\n% properties.\r\n%\r\n% First, a quick reminder, take a look at this special string class\r\n% called |FancyString| that enables decorating individual elements it the\r\n% string array with additional information such as hyperlinking or\r\n% bolding. This starts with the |FancyString| itself:\r\n%\r\n% <include>FancyString.m<\/include>\r\n%\r\n% As well as a couple decorators to add some fanciness:\r\n%\r\n% <include>DefaultDecorator.m<\/include>\r\n%\r\n% <include>HyperlinkDecorator.m<\/include>\r\n%\r\n% <include>BoldDecorator.m<\/include>\r\n%\r\n% Now we can have a nice message with some bolding and hyperlinking holiday cheer:\r\nholidayMessage = [\"Happy\" \"Holidays\" \"!\"];\r\n\r\ngreeting = FancyString(holidayMessage);\r\ngreeting(1).Decorator = BoldDecorator;\r\n\r\n% Add a link to US Holidays\r\nholidayWikipediaSite = 'https:\/\/en.wikipedia.org\/wiki\/List_of_multinational_festivals_and_holidays#December';\r\ngreeting(2).Decorator = HyperlinkDecorator(holidayWikipediaSite);\r\n\r\njoin([greeting.DecoratedValue])\r\n\r\n%%\r\n% Alright this is great, but there is a problem. Let's say we have an\r\n% enumeration containing the different holidays and we'd like to put\r\n% together a few different sets of greetings for our friends and neighbors\r\n% with different preferences. Maybe this looks something like this:\r\n%\r\n% <include>Holidays.m<\/include>\r\n%\r\n% That looks so nice I might just want to replace my string with one of\r\n% these enumeration values. Seems reasonable.\r\n%\r\ngreeting(2).PlainValue = Holidays.Kwanzaa  \r\n\r\n%%\r\n% So far so good. Quick spot check?\r\ngreeting.PlainValue\r\n\r\n%%\r\n% Still looks good at first glance. Alright how about the |DecoratedValue|?\r\n% Do the hyperlinking and bold operations still work? (hint: the\r\n% |try-catch| I've added in the script I am using to publish this blog is a\r\n% hint that something fishy might be going on):\r\n\r\ntry\r\n    greeting.DecoratedValue\r\ncatch e\r\n    disp('Errored!');\r\n    disp(e.getReport('basic'));\r\nend\r\n\r\n\r\n%%\r\n% Alright this doesn't work because I've assigned to the |PlainValue| a value\r\n% from our enumeration, but the |FancyString| (and the decorators) are\r\n% expecting the value to be a string.\r\n%\r\n% In fact, we could have supplied any arbitrary value to the property and we\r\n% likely wouldn't have noticed until much farther down the line. For\r\n% example, let's add a structure, which is meaningless in this context:\r\nmeaninglessStruct.SomeField = 5;\r\nmeaninglessStruct.AnotherField = true;\r\n\r\ngreeting(2).PlainValue = meaninglessStruct; % Assignment works!!\r\ngreeting.PlainValue % Still doesn't error!\r\n\r\n%%\r\n% It only errors when we use it farther down the line, such as in concatenation:\r\n\r\ntry\r\n    [greeting.PlainValue]\r\ncatch e\r\n    disp('Errored!');\r\n    disp(e.getReport('basic'));\r\nend\r\n\r\n%%\r\n% This is clearly not optimal. Property validation to the rescue! We can\r\n% make the simplest of tweaks to the |FancyString| so that we can always know\r\n% for sure that the |PlainValue| property will always be a string. It's as\r\n% easy as this slightly more fancy string implementation:\r\n%\r\n% <include>MoreFancyString.m<\/include>\r\n%\r\n% The only difference here is in the property block where plain value was\r\n% defined:\r\n%\r\n% |PlainValue (1,1) string|\r\n%\r\n% This states that the |PlainValue| must always be a scalar string, which\r\n% gives us much more peace of mind as we process that code. How does it\r\n% work now?\r\n%\r\ngreeting = MoreFancyString(holidayMessage);\r\ngreeting(1).Decorator = BoldDecorator;\r\ngreeting(2).Decorator = HyperlinkDecorator(holidayWikipediaSite);\r\ngreeting(2).PlainValue = Holidays.Kwanzaa \r\n\r\n%%\r\n% This time if you look closely you will see the enum was converted to a string\r\n\r\ngreeting(2).PlainValue\r\n\r\n%%\r\n% ...and because of that everything else like concatenation and the string\r\n% decoration works as expected:\r\njoin([greeting.PlainValue])\r\n\r\njoin([greeting.DecoratedValue])\r\n\r\n%%\r\n% It also correctly errors right away with bunk values that don't know how to be\r\n% represented as strings:\r\n\r\ntry\r\n    greeting(2).PlainValue = meaninglessStruct;\r\ncatch e\r\n    disp('Errored!');\r\n    disp(e.getReport('basic'));\r\nend\r\n\r\n%%\r\n% Awesome! A couple concluding thoughts:\r\n% \r\n% # We could have also given this guarantee by implementing a\r\n% |set.PlainValue| method that validates the input using the\r\n% |validateattributes| or otherwise. This would be certainly possible, and\r\n% a benefit of encapsulated properties. However, if this validation is all\r\n% that is needed property validators are much more convenient and\r\n% accessible.\r\n% # Classes that are convertible to the datatype specified (in this case\r\n% |string|) are automatically converted. In this case the enumeration\r\n% really knows how to be interpreted correctly as a string, and so it just\r\n% intuitively worked out of the box!\r\n% # This conversion has a flipside. What this really provides is a\r\n% guarantee that the actual stored value will be a |string|. However,you\r\n% can set non-string values to this property as long as they are\r\n% convertible to a string, and the conversion will be performed upon\r\n% setting the property. This is typically the right behavior, since the\r\n% value with a type conversion is the class that should be able to decide\r\n% that it can be interpeted as a string. However, if you find that you wish\r\n% to disallow any datatype from being assigned to the property unless it is\r\n% the precise type to start with, then you may need to leverage the setter\r\n% method instead to enforce that restriction directly.\r\n% \r\n% Have you used the new property validation features? I hope so. Actually\r\n% there is much more richness to property validation than I've shown here,\r\n% check out the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/validate-property-values.html\r\n% documentation>. I've hinted at size\/shape validation but there is also\r\n% the ability to pass validation functons to the value being set, as well\r\n% as a\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/property-validator-functions.html\r\n% rich library of validation functions> in MATLAB for your benefit. Let us\r\n% know what you think!....oh, and\r\n%\r\nholidays = enumeration('Holidays');\r\nfor idx = 1:numel(holidays)\r\n    greeting(2).PlainValue = holidays(idx);\r\n    if strcmp(holidays(idx), 'Christmas') % There's always a special case\r\n        specialGreeting = greeting;\r\n        specialGreeting(1).PlainValue = \"Merry\";\r\n        disp(join([specialGreeting.DecoratedValue]));\r\n        continue;\r\n    end\r\n    disp(join([greeting.DecoratedValue]));\r\nend\r\n\r\n%%\r\n%\r\n% <<y2017HolidayCheer.png>>\r\n##### SOURCE END ##### f9ef04c1f95344fea2a79134b96a75c6\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/developer\/files\/y2017HolidayCheer.png\" onError=\"this.style.display ='none';\" \/><\/div><p>Well, it's that time of year, Christmas, Hanukkah, Kwanzaa, Ramadan, Winter Solstice, or you know.......Friday. You deserve the gift of a blog post. Here's a nugget of object oriented goodness in... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/developer\/2017\/12\/22\/property-validation\/\">read more >><\/a><\/p>","protected":false},"author":90,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,5],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/1190"}],"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\/90"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/comments?post=1190"}],"version-history":[{"count":6,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/1190\/revisions"}],"predecessor-version":[{"id":1210,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/1190\/revisions\/1210"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/media?parent=1190"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/categories?post=1190"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/tags?post=1190"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}