Property validation in subclass
Mostrar comentarios más antiguos
Hello everyone, i am new to the OOP in Matlab.
I have a superclass SimpleList with the property set, which is an array with any kind of data in it.
classdef SimpleList < handle
% SimpleList
properties
set(:,1)
end
methods
.
.
.
end
end
And a subclass ObjList, where the array should only contain objects of a specific class
classdef ObjList < SimpleList
% ObjectList
properties
end
methods
.
.
.
end
end
My Question is: How do i validate the property in ObjList?
Thanks in advance!
Respuesta aceptada
Más respuestas (1)
In general I do this kind of thing via delegation from the superclass set function. Your property declaration confuses me though. Don't call a property 'set', it is asking for trouble. Also using (:,1) in the property block doesn't make much sense to me - is it even valid syntax there?
So to give an example:
classdef mySuperClass < handle
properties
myProp;
end
methods
function set.myProp( obj, myPropVal )
myPropVal = doValidateMyProp( obj, myPropVal );
obj.myProp = myPropVal;
end
end
methods( Access = protected )
function myPropVal = doValidateMyProp( obj, myPropVal )
end
end
end
classdef mySubClass < mySuperClass
methods( Access = protected )
function myPropVal = doValidateMyProp( obj, myPropVal )
% Do some validation
end
end
end
You don't have to return the value out of the function - it depends what type of validation you are doing. If you just want it to throw an error then get rid of the output type, but if, for example, you use validatestring the output argument can be useful.
I left the body of the doValidateMyProp function empty in the superclass - it is up to you what you put in here. Because I didn't make it abstract this will get called if your subclass does not override the function so it isn't compulsory for the subclass to do this.
1 comentario
Guillaume
el 4 de Abr. de 2017
Great minds think alike, or somesuch...
(:, 1) is indeed not valid. I assumed it was a typo.
I forgot to mention in my answer that if the base class is not meant to be used as a container on its own, then ideally it should be abstract.
Categorías
Más información sobre Properties en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!