How to implement a setter restriction?
Show older comments
When making a user-defined class myClass that inherits from matlab.mixin.SetGet, how can I restrict the Set for a property prop1? Say that I want to allow only true/false sets for a property.
classdef myClass < handle & matlab.mixin.SetGet
properties (Access = public)
prop1
end
methods
%% Setter restrictions
% This is what I would do if it weren't a subclass of matlab.mixin.SetGet {
function set.prop1(self,value)
% Prevent non-boolean input value sets.
if value == true
self.prop1 = true;
else
self.prop1 = false;
end
end
%}
end
end
I like the syntax of matlab.mixin.SetGet so I'd prefer to not code it this way.
5 Comments
Walter Roberson
on 31 Jan 2019
assert(isscalar(value) && islogical(value), 'Must be boolean scalar')
I would note, though, that it is very common for people to pass 0 for false or 1 for true, and that as far as MATLAB is concerned, anything non-zero non-nan is true.
Dominik Mattioli
on 31 Jan 2019
Walter Roberson
on 31 Jan 2019
It would go right after
% Prevent non-boolean input value sets.
Are you hoping for a mechanism to add type restrictions on the calls themselves, such as (hypothetically) through the methods attributes list, so that MATLAB does the type filtering for you, without you having to put in a type check yourself ?
Dominik Mattioli
on 31 Jan 2019
Walter Roberson
on 31 Jan 2019
If you want to permit 0 and 1 as well as true and false, then I note that ismember() of 0 or 1 against true false works, and ismember() of true or false against 0 1 works, and that true == 1 and 0 == false work.
Accepted Answer
More Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!