How can I define a class constant based on an abstract constant?
Show older comments
I am trying to write an abstract class with constant properties. One of these constant properties depends on the others, but will be computed the same way for each sub-class.
Here is a simple contrived minimum example of what I am trying to achieve:
classdef (Abstract) BaseData
properties (Abstract = true, Constant = true)
data;
end
properties (Constant = true)
avg = mean(BaseData.data); % Doesn't work as desired
end
properties
% ...
end
methods
% ...
end
end
classdef TestData < BaseData
properties (Constant = true)
data = [1, 2, 3, 4, 5];
end
end
In this example I would like avg to be computed and saved as a class constant for each sub-class I write.
Some solutions I have thought of:
(1) The above
avg is empty because BaseData.data is empty when the command is run.
(2) Compute avg in each sub-class
I could do this, but it is duplicate code.
(3) Store avg as an immutable property and compute it in the constructor for the class
This solution is not quite what I want either. For every TestData object I make, the exact same computation is performed to get the exact same result each time. In addition, the property is stored on a per-object basis instead of at class scope.
1 Comment
Jacob Lynch August
on 10 Aug 2021
A good solution is one that does not obfuscate the codes' structure or intention, and the two workarounds (replicate code in each subclass, calculate on construct) unforuntately do just that.
A third, bad workaround would memoize results.
classdef (Abstract) AbstractClass
properties(Abstract,Constant)
data
end
properties(Dependent)
avg
end
methods
function m = get.avg(obj)
f = memoize(@mean);
m = f(obj.data);
end
end
end
classdef DefiniteClass < AbstractClass
properties(Constant)
data = 1:5;
end
end
I wish there was a better way to accomplish this, as I have large data that should be loaded/processed only once, and each subclass specifies what is that large block of data and how it is processed.
Accepted Answer
More Answers (0)
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!