Set methods for two interdependent properties in class: how do I avoid infinite recursion?
이전 댓글 표시
I want to define a class where two properties depend on each other. This means that each set method should modify the other property accordingly.
Simplified example: let's say I define a class for a car, that contains its speed in different units:
classdef Car
properties
speed_km_h = 0;
speed_mph = 0;
end
methods
function obj = set.speed_km_h(obj, value)
obj.speed_km_h = value;
obj.speed_mph = value / 1.61;
end
function obj = set.speed_mph(obj, value)
obj.speed_mph = value;
obj.speed_km_h = value * 1.61;
end
end
end
Implemented like above, asigning a value to one of the properties results in an infinite recursion loop, since each set method calls the other one:
c = Car;
c.speed_km_h = 30;
Out of memory. The likely cause is an infinite recursion within the program.
What's the corrent way to implement this kind of functionality?
Some notes:
- In the simple example above, having one of the values be a dependent property might be a better solution, but I'm asking explicitly about two properties that actually store these values seperatly in the object.
- Defining the properties with AbortSet breaks the recursion and makes the example work, but only if the third setter in the recursion stack tries to set the same value as the original one. If e. g. one of the unit conversions were to introduce a rounding error, the recursion would happen again. There must be a more elegant way, right?
댓글 수: 4
Steven Lord
2022년 11월 7일
I'd use the dependent property approach you cited in your last parenthetical comment. Store the speed in one of the units as a concrete property and have property accessor methods for the other that performs the conversion when that other property is assigned to or referenced.
If you have a realistic example where that is not possible or is less desirable, please describe your actual example in more detail so we can offer more relevant suggestions.
fi
2022년 11월 7일
The appropriate recommendation depends on how they will be accessed (read or write) and how often in each case. If they will only be read-accessed often, then you may as well just compute both properties once in the constructor and make them Immutable. No need for set.property methods.
If they need to be write-accessed often, there is no benefit to storing them both. The same computations will be required to keep them consistent whether one of the properties is Dependent or not. In fact, it would be more benefical to have one property Dependent, because then only the concrete property needs to be updated in a write operation.
fi
2022년 11월 9일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!