OOP: lazy dependent property

11 views (last 30 days)
Drew
Drew on 16 May 2013
In a class, I have a dependent property that's expensive to calculate. It only depends on one other property, call it "value" in the class, so I'm trying to prevent it from re-calculating unless value changes.
The snippet below works, but it shows a warning about setting the property value for lazy in the set method for value. Is there a better way to do this?
classdef MyClass < handle
properties
value;
end
properties (Dependent)
output;
end
properties (Access = private)
lazy = false;
cachedOutput;
end
methods
function obj = MyClass(value)
obj.value = value;
end
function set.value(obj, value)
obj.lazy = false; % warning here
obj.value = value;
end
function res = get.output(obj)
if obj.lazy
res = obj.cachedOutput;
else
res = expensive_function(obj.value);
obj.cachedOutput = res;
obj.lazy = true;
end
end
end
end
function res = expensive_function(value)
res = value + 1;
end

Accepted Answer

per isakson
per isakson on 16 May 2013
Edited: per isakson on 16 May 2013
I've seen a recommendation to use persistent variables in expensive_function
function res = expensive_function(value)
persistent old_value old_res
if not( isempty( old_value ) ) && value == old_value
res = old_res;
else
res = value + 1;
old_res = res;
old_value = value;
end
end
whether it is better I don't know.
  4 Comments
per isakson
per isakson on 17 May 2013
I seldom use dependent properties. They used to cause me problems when coding and debugging. That was because the get-method was called by display and tooltip functions. An error in the get-method tended to produce mess.
I prefer not to include expensive_function in the get-method. A few reasons:
  • I want to keep the get-method as simple as possible
  • A separate expensive_function is easier to test.
  • Given that expensive_function is expensive the time to call an extra function is negligible
  • I don't understand the oop-argument not to use ordinary functions together with classes.
Sean de Wolski
Sean de Wolski on 17 May 2013
@Matt J, I would vote for that:
get.output

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!