{"id":268,"date":"2011-03-08T17:57:27","date_gmt":"2011-03-08T17:57:27","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/03\/08\/common-design-considerations-for-object-properties\/"},"modified":"2011-03-16T11:47:13","modified_gmt":"2011-03-16T11:47:13","slug":"common-design-considerations-for-object-properties","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/03\/08\/common-design-considerations-for-object-properties\/","title":{"rendered":"Common Design Considerations for Object Properties"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I&#8217;m pleased to introduce guest blogger Dave Foti.  Dave has worked on MATLAB for over 15 years and currently manages the group\r\n         responsible for object-oriented programming features in MATLAB.  He is interested in giving MATLAB users the tools to meet\r\n         increasingly complex challenges. This post will take a look at making use of object properties in MATLAB.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Property Basics<\/a><\/li>\r\n         <li><a href=\"#4\">Dependent Properties<\/a><\/li>\r\n         <li><a href=\"#6\">Changing Property Names<\/a><\/li>\r\n         <li><a href=\"#8\">Side Effects and Validation<\/a><\/li>\r\n         <li><a href=\"#10\">Default Values<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Property Basics<a name=\"1\"><\/a><\/h3>\r\n   <p>Properties are how MATLAB objects store data.  At their most basic level, properties provide a way to define what data are\r\n      required for a particular kind of object.  For example, if I have a set of measurements and each measurement has the same\r\n      pieces of information, then I can create a class of measurement objects with a property to store each piece of information\r\n      as in:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading1<\/span><\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading1\r\n  properties\r\n    Date\r\n    Latitude\r\n    Longitude\r\n    Temperature\r\n  end\r\nend\r\n<\/pre><p>I might have an instance that looks like this:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">t1 = surfaceTempReading1;\r\nt1.Date = date;\r\nt1.Latitude  = <span style=\"color: #A020F0\">'42:16:4 N'<\/span>;\r\nt1.Longitude = <span style=\"color: #A020F0\">'71:20:2 W'<\/span>;\r\nt1.Temperature = 260;\r\ndisp(t1);<\/pre><pre style=\"font-style:oblique\">  surfaceTempReading1\r\n\r\n  Properties:\r\n           Date: '16-Mar-2011'\r\n       Latitude: '42:16:4 N'\r\n      Longitude: '71:20:2 W'\r\n    Temperature: 260\r\n<\/pre><p>The MATLAB documentation describes properties <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_oop\/brqy3km-9.html\">here<\/a>.\r\n   <\/p>\r\n   <h3>Dependent Properties<a name=\"4\"><\/a><\/h3>\r\n   <p>In simple cases like this, it is probably fine to have all properties directly store and retrieve data.  However, MATLAB provides\r\n      ways to define properties that don&#8217;t directly store data.  These dependent properties are defined using the <tt>Dependent<\/tt> attribute as in:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading2<\/span><\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading2\r\n  properties\r\n    Date\r\n    Latitude\r\n    Longitude\r\n    Temperature\r\n  end\r\n\r\n  properties(Dependent)\r\n    Altitude\r\n  end  \r\n\r\n  methods\r\n    function A = get.Altitude(reading)\r\n      A = lookupAltitude(reading.Latitude, reading.Longitude);\r\n    end\r\n  end\r\nend\r\n<\/pre><p>In this case, if I have a data set of surface temperature readings, I just need latitude and longitude to identify where the\r\n      temperature was sampled.  However, in analyzing the data, it might be helpful to correlate temperatures with surface altitude.\r\n       Rather than have to input this data, the altitude can be calculated from a database of Earth surface topography.  Assume\r\n      I have a function that can provide such a value called <tt>lookupAltitude<\/tt>, then I can invoke that function from the <tt>Dependent<\/tt> property called <tt>Altitude<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">t2 = surfaceTempReading2;\r\nt2.Date = date;\r\nt2.Latitude  = <span style=\"color: #A020F0\">'42:16:4 N'<\/span>;\r\nt2.Longitude = <span style=\"color: #A020F0\">'71:20:2 W'<\/span>;\r\nt2.Temperature = 260;\r\ndisp(t2)<\/pre><pre style=\"font-style:oblique\">  surfaceTempReading2\r\n\r\n  Properties:\r\n           Date: '16-Mar-2011'\r\n       Latitude: '42:16:4 N'\r\n      Longitude: '71:20:2 W'\r\n    Temperature: 260\r\n       Altitude: 342\r\n<\/pre><h3>Changing Property Names<a name=\"6\"><\/a><\/h3>\r\n   <p><tt>Dependent<\/tt> properties allow me some flexibility to implement the same external interface in different ways.  A user of our class doesn&#8217;t\r\n      necessarily need to know how altitude was determined or whether or not it is actually stored in a class instance.  This flexibility\r\n      can be useful in evolving a class over time while not breaking scripts and functions that might use the class.  For example,\r\n      if I decide that <tt>TimeStamp<\/tt> is a better name for the <tt>Date<\/tt> property, I can gradually start switching over to the new name without immediately changing all of the code I have using\r\n      <tt>Date<\/tt>:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading3<\/span><\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading3\r\n  properties\r\n    TimeStamp\r\n    Latitude\r\n    Longitude\r\n    Temperature\r\n  end\r\n  \r\n  % Deprecated property names\r\n  properties(Dependent, Hidden) \r\n    Date\r\n  end\r\n\r\n  methods\r\n    function D = get.Date(reading)  \r\n      D = reading.TimeStamp;\r\n    end\r\n\r\n    function reading = set.Date(reading, D)\r\n      reading.TimeStamp = D;\r\n    end\r\n  end\r\nend\r\n<\/pre><p>When I change my class as above, not only will old scripts using <tt>Date<\/tt> continue to work, but old MAT-Files saved using the old class definition will automatically load the <tt>Date<\/tt> value into the new <tt>TimeStamp<\/tt> property. I use the <tt>Hidden<\/tt> attribute so that the old property name doesn&#8217;t show up in object display, the <tt>properties<\/tt> command, or tab completion.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">t3 = surfaceTempReading3;\r\nt3.Date = date;\r\ndisp(t3);<\/pre><pre style=\"font-style:oblique\">  surfaceTempReading3\r\n\r\n  Properties:\r\n      TimeStamp: '16-Mar-2011'\r\n       Latitude: []\r\n      Longitude: []\r\n    Temperature: []\r\n<\/pre><h3>Side Effects and Validation<a name=\"8\"><\/a><\/h3>\r\n   <p><tt>Dependent<\/tt> properties can also be useful any time a property has side effects &#8211; when for example changing a property triggers an update\r\n      to some other object or graphic or when getting a property requires doing some expensive operation to acquire or validate\r\n      the result.  Often these expensive operations can be avoided from certain \"trusted\" code defined inside the class.  Having\r\n      a one private property that doesn&#8217;t perform any side effects allows the trusted code to work on the raw property value. Other\r\n      code inside and outside the class can use a public and dependent property that performs the side effects or expensive operations.\r\n      Sometimes the expensive operation is just validating the input value being assigned to the property.  For example, in our\r\n      class if I want to validate temperature values, I can do something like the following:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading4<\/span>;<\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading4\r\n  properties\r\n    Date\r\n    Latitude\r\n    Longitude\r\n  end\r\n  properties (Dependent)\r\n    Temperature\r\n  end\r\n  \r\n  properties(Access=private)\r\n    pTemperature\r\n  end\r\n\r\n  methods\r\n    function reading = set.Temperature(reading, t)\r\n      if t &lt; 0 \r\n        error('SurfaceTemp:BadTemp', ...\r\n              'Temperature must be a positive number in Kelvins.');\r\n      end\r\n      reading.pTemperature = t;\r\n    end\r\n    function t = get.Temperature(reading)\r\n        t = reading.pTemperature;\r\n    end\r\n  end\r\nend\r\n<\/pre><p>NOTE: The above example has been changed to correct an error in the original post.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">t4 = surfaceTempReading4;\r\n<span style=\"color: #0000FF\">try<\/span>\r\n    t4.Temperature = -15;\r\n<span style=\"color: #0000FF\">catch<\/span> err\r\n    disp(err.message);\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">Temperature must be a positive number in Kelvins.\r\n<\/pre><h3>Default Values<a name=\"10\"><\/a><\/h3>\r\n   <p>Classes can define default values for properties.  A default value is defined by the class and each instance of the class\r\n      is assigned that default value.  Default values can be used when there is a constant default that can be documented with the\r\n      class definition.  Default values can save space in MAT-Files because defaults are saved once per class and values of properties\r\n      not differing from default values don&#8217;t need to be saved.  Generally speaking default values should be literal values wherever\r\n      possible so that it is clear what the default is.  For example:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading5<\/span><\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading5\r\n  properties\r\n    Date\r\n    Latitude = '0N';\r\n    Longitude = '0E';\r\n    Temperature = 0;\r\n  end\r\nend\r\n<\/pre><p>While it is possible to use the result of a function for a default value, one should avoid doing so unless the function returns\r\n      a constant value. For example, it might be tempting to do something like:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">surfaceTempReading6<\/span><\/pre><pre style=\"font-style:oblique\">\r\nclassdef surfaceTempReading6\r\n  properties\r\n    % Get the current date from MATLAB\r\n    Date = date; \r\n    \r\n    Latitude\r\n    Longitude\r\n    Temperature\r\n  end\r\nend\r\n<\/pre><p>However, the problem with this is that the current date is not a constant default value that can be documented as part of\r\n      the class.  Moreover, since MATLAB evaluates default property expressions in class definitions only when a class is loaded\r\n      or reloaded, the function call will generally happen once in a MATLAB session.  Each object will get the same date stamp that\r\n      was current when the class was loaded and not the current date at the time an object is created (perhaps the next day).  Generally,\r\n      one doesn&#8217;t want to assign a default value to a handle for a similar reason. If the intent is to make a new handle for each\r\n      instance, then this handle has to be created in the constructor and not as a default value.  Since defaults are the same for\r\n      all instances created from a given class definition, all objects would get the same handle.  For more information on handle\r\n      classes, see <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_oop\/brfylwk-1.html\">Handle and Value Classes<\/a>.\r\n   <\/p>\r\n   <p>I&#8217;ve described a few uses for properties and a few common attributes, but I would be very interested in hearing how you use\r\n      properties.  You can post ideas <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=268#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_2491832154e640cf880163d8944b9a9d() {\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='2491832154e640cf880163d8944b9a9d ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 2491832154e640cf880163d8944b9a9d';\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        author = 'Dave Foti';\r\n        copyright = 'Copyright 2011 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 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');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \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_2491832154e640cf880163d8944b9a9d()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.11<br><\/p>\r\n<\/div>\r\n<!--\r\n2491832154e640cf880163d8944b9a9d ##### SOURCE BEGIN #####\r\n%% Common Design Considerations for Object Properties\r\n% I\u00e2\u20ac\u2122m pleased to introduce guest blogger Dave Foti.  Dave has worked on \r\n% MATLAB for over 15 years and currently manages the group responsible for \r\n% object-oriented programming features in MATLAB.  He is interested in \r\n% giving MATLAB users the tools to meet increasingly complex challenges. \r\n% This post will take a look at making use of object properties in MATLAB.\r\n%% Property Basics\r\n% Properties are how MATLAB objects store data.  At their most basic level, \r\n% properties provide a way to define what data are required for a \r\n% particular kind of object.  For example, if I have a set of measurements \r\n% and each measurement has the same pieces of information, then I can \r\n% create a class of measurement objects with a property to store each \r\n% piece of information as in:\r\ntype surfaceTempReading1\r\n%%\r\n% I might have an instance that looks like this:\r\nt1 = surfaceTempReading1;\r\nt1.Date = date;\r\nt1.Latitude  = '42:16:4 N'; \r\nt1.Longitude = '71:20:2 W'; \r\nt1.Temperature = 260;\r\ndisp(t1);\r\n%%\r\n% The MATLAB documentation describes properties\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_oop\/brqy3km-9.html here>.\r\n%% Dependent Properties\r\n% In simple cases like this, it is probably fine to have all properties \r\n% directly store and retrieve data.  However, MATLAB provides ways to \r\n% define properties that don\u00e2\u20ac\u2122t directly store data.  These dependent\r\n% properties are defined using the |Dependent| attribute as in:\r\ntype surfaceTempReading2\r\n%%\r\n% In this case, if I have a data set of surface temperature readings, \r\n% I just need latitude and longitude to identify where the temperature was \r\n% sampled.  However, in analyzing the data, it might be helpful to \r\n% correlate temperatures with surface altitude.  Rather than have to input \r\n% this data, the altitude can be calculated from a database of Earth \r\n% surface topography.  Assume I have a function that can provide such a \r\n% value called |lookupAltitude|, then I can invoke that function from the \r\n% |Dependent| property called |Altitude|.\r\nt2 = surfaceTempReading2;\r\nt2.Date = date;\r\nt2.Latitude  = '42:16:4 N'; \r\nt2.Longitude = '71:20:2 W'; \r\nt2.Temperature = 260;\r\ndisp(t2)\r\n%% Changing Property Names\r\n% |Dependent| properties allow me some flexibility to implement the same \r\n% external interface in different ways.  A user of our class doesn\u00e2\u20ac\u2122t \r\n% necessarily need to know how altitude was determined or whether or not it\r\n% is actually stored in a class instance.  This flexibility can be useful \r\n% in evolving a class over time while not breaking scripts and functions \r\n% that might use the class.  For example, if I decide that |TimeStamp| is a\r\n% better name for the |Date| property, I can gradually start switching over\r\n% to the new name without immediately changing all of the code I have using\r\n% |Date|:\r\ntype surfaceTempReading3\r\n%%\r\n% When I change my class as above, not only will old scripts using |Date| \r\n% continue to work, but old MAT-Files saved using the old class definition \r\n% will automatically load the |Date| value into the new |TimeStamp| property.  \r\n% I use the |Hidden| attribute so that the old property name doesn\u00e2\u20ac\u2122t show up \r\n% in object display, the |properties| command, or tab completion.\r\nt3 = surfaceTempReading3;\r\nt3.Date = date;\r\ndisp(t3);\r\n%% Side Effects and Validation\r\n% |Dependent| properties can also be useful any time a property has side \r\n% effects \u00e2\u20ac\u201c when for example changing a property triggers an update to some\r\n% other object or graphic or when getting a property requires doing some \r\n% expensive operation to acquire or validate the result.  Often these \r\n% expensive operations can be avoided from certain \"trusted\" code defined \r\n% inside the class.  Having a one private property that doesn\u00e2\u20ac\u2122t perform any\r\n% side effects allows the trusted code to work on the raw property value.  \r\n% Other code inside and outside the class can use a public and dependent \r\n% property that performs the side effects or expensive operations.  \r\n% Sometimes the expensive operation is just validating the input value \r\n% being assigned to the property.  For example, in our class if I want to \r\n% validate temperature values, I can do something like the following:\r\ntype surfaceTempReading4;\r\n%%\r\n% NOTE: The above example has been changed to correct an error in the \r\n% original post.\r\nt4 = surfaceTempReading4;\r\ntry\r\n    t4.Temperature = -15;\r\ncatch err\r\n    disp(err.message);\r\nend\r\n%% Default Values\r\n% Classes can define default values for properties.  A default value is \r\n% defined by the class and each instance of the class is assigned that \r\n% default value.  Default values can be used when there is a constant \r\n% default that can be documented with the class definition.  Default values\r\n% can save space in MAT-Files because defaults are saved once per class and\r\n% values of properties not differing from default values don\u00e2\u20ac\u2122t need to be \r\n% saved.  Generally speaking default values should be literal values \r\n% wherever possible so that it is clear what the default is.  For example:\r\ntype surfaceTempReading5\r\n%%\r\n% While it is possible to use the result of a function for a default value, \r\n% one should avoid doing so unless the function returns a constant value.  \r\n% For example, it might be tempting to do something like:\r\ntype surfaceTempReading6\r\n%%\r\n% However, the problem with this is that the current date is not a constant\r\n% default value that can be documented as part of the class.  Moreover, \r\n% since MATLAB evaluates default property expressions in class definitions \r\n% only when a class is loaded or reloaded, the function call will generally\r\n% happen once in a MATLAB session.  Each object will get the same date \r\n% stamp that was current when the class was loaded and not the current date\r\n% at the time an object is created (perhaps the next day).  Generally, one \r\n% doesn\u00e2\u20ac\u2122t want to assign a default value to a handle for a similar reason.  \r\n% If the intent is to make a new handle for each instance, then this handle\r\n% has to be created in the constructor and not as a default value.  Since \r\n% defaults are the same for all instances created from a given class \r\n% definition, all objects would get the same handle.  For more information \r\n% on handle classes, see\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_oop\/brfylwk-1.html Handle and Value Classes>.\r\n%%\r\n% I\u00e2\u20ac\u2122ve described a few uses for properties and a few common attributes, but \r\n% I would be very interested in hearing how you use properties.  You can\r\n% post ideas\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=268#respond here>.\r\n\r\n##### SOURCE END ##### 2491832154e640cf880163d8944b9a9d\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I&#8217;m pleased to introduce guest blogger Dave Foti.  Dave has worked on MATLAB for over 15 years and currently manages the group\r\n         responsible for object-oriented programming... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/03\/08\/common-design-considerations-for-object-properties\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[44],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/268"}],"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=268"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/268\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=268"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=268"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=268"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}