MATLAB Object-Oriented Programming

(Joyce) #1
For example, suppose that you have a class that changes the name of a property from
OldPropName to NewPropName. You can continue to allow the use of the old name
without exposing it to new users. To support the old property name, define OldPropName
a dependent property with set and get methods:

properties
NewPropName
end
properties (Dependent, Hidden)
OldPropName
end
methods
function obj = set.OldPropName(obj,val)
obj.NewPropName = val;
end
function value = get.OldPropName(obj)
value = obj.NewPropName;
end
end

There is no memory wasted by storing both old and new property values. Code that
accesses OldPropName continues to work as expected. Setting the Hidden attribute of
OldPropName prevents new users from seeing the property.

Assignments made from property set methods cause the execution of any set methods
defined for properties being set. See “Calculate Data on Demand” on page 3-23 for an
example.

Private Set Access with Dependent Properties


If you use a dependent property only to return a value, then do not define a set access
method for the dependent property. Instead, set the SetAccess attribute of the
dependent property to private. For example, consider the following get method for the
MaxValue property:

methods
function mval = get.MaxValue(obj)
mval = max(obj.BigArray(:));
end
end

This example uses the MaxValue property to return a value that it calculates only when
queried. For this application, define the MaxValue property as dependent and private:

8 Properties — Storing Class Data

Free download pdf