I’m trying to implement a class with a property that can be possibly provided to the constructor or possibly generated in some other method. I don’t want the data saved to disk or generated on load. What I have so far is:
classdef MyClass
properties(GetAccess = public, SetAccess = private)
Property1
Property2
Property3
end
properties(Access = private)
Property4
end
properties(Transient = true)
ProblemProperty
end
properties(Dependent = true, Transient = true)
Property5
end
methods
function MyClass
% Constructor.
end
function val = get.Property5(B)
val = SomeFunction(Property1);
end
function val = get.ProblemProperty(B)
if isempty(B.ProblemProperty)
B = GenerateProblemProperty(B);
end
val = B.ProblemProperty;
end
function B = GenerateProblemProperty(B)
B.ProblemProperty = AnotherFunction(B.Property2);
end
end
end
The problem is that when I try to save the object to disk, Matlab calls the get.ProblemProperty method (confirmed by running the profiler on just the save statement). The ProblemProperty field is empty and I want it to stay that way. It doesn’t call the get.Property5 method.
How do I avoid the call to get.ProblemProperty?
Since the property can sometimes be set (i.e. in the constructor) then this property is not strictly dependent. One solution is to store the settable value in a private property (
CustomProblemPropertyin the example below) in the constructor. Thegetmethod ofProblemPropertywould then check return this private property value if it’s not empty and otherwise return the generated value.