Effacer les filtres
Effacer les filtres

Why are setters called when loading a class from a file?

2 vues (au cours des 30 derniers jours)
Andrew Haselgrove
Andrew Haselgrove le 3 Août 2017
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.

Réponses (1)

Milind Jain
Milind Jain le 8 Août 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.

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by