Why are setters called when loading a class from a file?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Milind Jain
el 8 de Ag. de 2017
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 comentarios
Ver también
Categorías
Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!