Clear Filters
Clear Filters

Property Validation fails due to assignment issues.

2 views (last 30 days)
Hey everyone,
I'm trying to implement some property validation function for a class as follows
classdef test
properties
Str {mustBeString(Str)}
end
methods
function obj = test(str)
obj.Str = str;
end
end
end
function mustBeString(str)
% MUSTBESTRING checks if argument is a string
if ~isstring(str) && ~ischar(str)
error('Parameter:wrongType',...
'Description must be string.');
end
end
But here's the problem. It doesn't matter which value or type Str has, because matlab seems to assign an empty value for this property even before the constructor is evaluated. In fact I checked in debugging mode and it seems that the validation function is called before the constructor.
I also tried to execute a modified example from the matlab documentation
classdef ImData
properties
Data {mustBeNumeric, mustBeInRange(Data,[0,255])}
end
methods
function obj = ImData(dat)
obj.Data = dat;
end
end
end
function mustBeInRange(a,b)
if any(a(:) < b(1)) || any(a(:) > b(2))
error(['Value assigned to Data property is not in range ',...
num2str(b(1)),'...',num2str(b(2))])
end
end
In this case everything worked fine.
Anyone who might have an idea, how to fix this issue?
Thank you very much.

Answers (1)

Nirav Sharda
Nirav Sharda on 18 Apr 2017
The documentation page of Property Validation mentions that you should add a default value. Also in the example mentioned in the document they have set the default value of the Data which is numeric to 0. You can in your case set it to empty string or char array. You can modify your code to:
Str {mustBeString(Str)} = ''
I hope this helps.

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!