Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.
|
|
Nicolas
Posts:
4
Registered:
7/23/09
|
|
Ensuring class of property / Organizing data in multiple classes
Posted:
Nov 4, 2009 9:42 AM
|
|
Hello folks,
when developing a class containing properties of several other classes, I did not get the clue yet how to ensure that a property is always of a specific class or a set of classes.
Let there be the following class: [code] classdef classA < handle properties b; % should be of class classB c; % should be of class classC or classD end end [/code] When assigning a value to a property, like: [code] >> a = classA; >> a.b = 1; [/code] this should result in an error, since "1" is of class double but not classB.
I tried with modyfying set functions, like:
[code] function set.b(obj,inp) % Ensure that property "obj.b" is an instance of class "classB". % objectclass = 'classB'; objectname = 'b';
% Ensure property is existing if isempty(obj.(objectname)) %if isempty(obj.b) obj.(objectname) = eval(objectclass); %obj.b = classB(); elseif isa(obj.(objectname),objectclass) %isa(obj.b,'classB'); % All OK else error('Invalid class of ''%s'': %s, should be %s',objectname,class(obj.(objectname)),objectclass); end
% Test Parameters if nargin > 2 warning('This function has never been tested with more inputs than one'); elseif nargin == 1 error('This should never happen - it''s an input function.'); end
% Pass parameters name = char(fieldnames(inp)); if isproperty(obj.(objectname),name) obj.(objectname).(name) = inp.(name); else error('%s is no valid fieldname',name); end end [/code]
which has two disadvantages (I fould out until now): - it has to be define seperately as set function for each property of an object - it causes me a headache when trying to deal with object arrays, like
[code] >> a.b(1).field = 'b1'; >> a.b(2).field = 'b2'; >> a.b(3) = classB(classBinput); [/code]
This leads me to two questions: - Has anybody found a suitable way to ensure properties' classes? - How can one deal with indexing in set functions? Greetings to everybody who read until here, Nicolas
|
|
|
|