Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Ensuring class of property / Organizing data in multiple classes
Replies: 3   Last Post: Nov 5, 2009 9:44 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Nicolas

Posts: 4
Registered: 7/23/09
Ensuring class of property / Organizing data in multiple classes
Posted: Nov 4, 2009 9:42 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2009. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Goodwin College of Professional Studies.