How to efficiently use dependent properties if dependence is computational costly?
53 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Michael Baumgart
el 8 de Mayo de 2014
Comentada: Vaughan Clarkson
el 28 de Mayo de 2024
Hello!
I want to design a class where some properties are dependent on others. I understand the general concept of Matlab OOP for dependent properties: the property is recalculated each time it is accessed.
But if these calculations/dependencies are costly and the dependent properties are often accessed by methods within the class, what are you suggesting to do. Basically, it would suffice to recalculated the property each time its parents properties are updated.
If I do so, I get a warning that accessing another property from the set method of an independent property is not recommended. What else can I do?
Cheers Michael
0 comentarios
Respuesta aceptada
Jacob Halbrooks
el 8 de Mayo de 2014
Editada: Jacob Halbrooks
el 8 de Mayo de 2014
I would recommend you add a method to compute and update the value of your dependent property and then call that method from the setters for each property that updates it. This single-sources the computation of that property, caches it to avoid unnecessary re-computation, and satisfies MATLAB Code Analyzer.
Here is an example, where Area of a Rectangle depends on Width and Height and is updated when each of those is set:
classdef Rectangle < handle
properties
Width = 10;
Height = 20;
end
properties(SetAccess = private)
Area = 200;
end
methods
function set.Width(obj, v)
obj.Width = v;
obj.updateArea;
end
function set.Height(obj, v)
obj.Height = v;
obj.updateArea;
end
end
methods(Access = private)
function updateArea(obj)
obj.Area = obj.Width * obj.Height;
end
end
end
8 comentarios
Jan Kappen
el 5 de Mzo. de 2024
I'm using that pattern in handle classes too, but how to implement it in value classes? Updating dependent properties in the update Method does not work because the setter & getter do not return the object.
Thanks :)
Vaughan Clarkson
el 28 de Mayo de 2024
It would be a nice addition to the Matlab language if there were a "Dependent = push" option or similar (vs. a default of "Dependent = pull") which could automatically execute the equivalent of the set and update methods that @Jacob Halbrooks defines above. It would save the programmer a lot of refactoring effort whenever it's discovered that the "push" paradigm is more efficient than "pull".
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!