Why are setters called when loading a class from a file?
1 次查看(过去 30 天)
显示 更早的评论
I am trying to create a class which represents a tridiagonal matrix as 3 vectors. The main point of this class is error-checking - for example, when I modify values, I want to ensure that I am not changing the size of any of the vectors. Hence, I have created setters to implement this logic.
I have a property which represents the size of my matrix, and M-Lint is throwing warnings about the use of this property: 'A set method for a non-Dependent property should not access another property'. A bit of research suggests that this warning is in place to prevent an issue which might occur when loading the class from a file (that I have no control over the order in which MATLAB loads properties). However, this confuses me - why is there any need for the setters to be called in this case? When I saved the data, it was in a valid state. Hence, it will be valid when loading back into MATLAB.
0 个评论
回答(1 个)
Milind Jain
2017-8-8
classdef MyClass < matlab.mixin.SetGet
properties
Prop1 = 6
Prop2 = 5
end
methods
function set.Prop1(obj,value)
if (value > obj.Prop2)
obj.Prop1 = value;
else
error('Property value must be greater than prop2')
end
end
end
end
the error can be suppressed by using the non-dependent property outside the setter of the other property. As shown below
classdef MyClass < matlab.mixin.SetGet
properties
Prop1 = 6
Prop2 = 5
end
methods
function set.Prop1(obj,value)
if (validate(obj,value))
obj.Prop1 = value;
else
error('Property value must be greater than prop2')
end
end
% validation outside
function y = validate(obj, value)
y = (value > obj.Prop2);
end
end
end
PS: The warning message is thrown so as to make users aware that MATLAB would reach an ambiguity if multiple initializations occur on the same property.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!