[Warning] Why is it bad practice to set additional class properties when using a set method (prompting a warning)?
Ältere Kommentare anzeigen
I have a class with several properties, and I want it so that if I set one of those properties, it effectively resets additional properties. Now, these are not fully dependent properties, since I want to be able to manipulate them as well. Here is a MWE
classdef testClass
properties
A(2,1) double = [5;1];
B(1,1) double
end
methods
function obj = set.A(obj,val)
obj.A = val;
obj.B = sum(obj.A); % This is where the warning pops in
end
function obj = doThing(obj)
obj.B = 2*obj.B;
end
end
end
The warning reads "The set method for propery 'A' should not access another property ('B')". The more detailed warning talks about dependency issues and ordering. Now, again, B is not a dependent or transient property.
I know I can do various things to make sure that there are no errors because of this: 'B' initializes as 0 because I have defined it in the properties block, and I can get the "proper" starting value by including something like this in the constructor:
function obj = testClass
obj.B = sum(obj.A);
end
So, my question is whether this is still bad coding practice despite taking care that properties are appropriately set? Is there another, better way of resetting certain semi-dependent properties when another property is modified.
Cheers,
-DP
Akzeptierte Antwort
Weitere Antworten (1)
The thing is that dependent properties always invoked their get/set methods every time you access them. what you did doesn't necessarily create bugs. But to be on the safe side and get rid of the warning you can make A a dependent property and have it save its value in a private property, let's call it A_:
classdef testClass
properties (GetAccess=private,SetAccess=private)
A_(2,1) double = [5,1];
end
properties
B(1,1) double;
end
properties (Dependent)
A;
end
methods
function obj = set.A(obj,val)
obj.A_ = val;
obj.B = sum(obj.A);
end
function a = get.A(object)
a = object.A_;
end
function obj = doThing(obj)
obj.B = 2*obj.B;
end
end
end
Kategorien
Mehr zu Properties finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!