Prev: Problem with matrix in a Simulink bus.
Next: cannot build matlab embedded functions in simulink
From: David Young on 13 Apr 2010 06:37 I'd like to write a class constructor that takes property/value pairs as arguments, checks that the property strings match public properties of the class, and assigns the values to them as appropriate. I wondered if anyone knows of any tools that already exist to help with this task. In more detail: Suppose I have a value class with lots of properties classdef propRich properties a = 33; b = 'bval'; % and several more end methods function pr = propRich(varargin) % initialise properties end end end and I want to be able to create an instance by writing pr = propRich('a', -15); so that in the new instance property a will have the value -15 but property b will have its default value 'bval'. Clearly, it's error-prone to duplicate the property names in the constructor, so I'll use the ? operator to get them and then do validation on the arguments. I'd hoped that inputParser would help with this, but it looks like using it will be quite clumsy, if only because I want to keep the default values in the properties block for clarity, and not buried in the constructor. I suppose I could subclass hgsetget, but my class isn't otherwise a candidate for being a handle class, and I much prefer to retain value class semantics wherever possible. So before I start writing code that will duplicate some of what inputParser and hgsetget do, I thought I'd ask if anyone has any suggestions. Answers of the form "you shouldn't be trying to do this anyway, there's a better way to provide the functionality " would of course be welcome!
From: David Young on 13 Apr 2010 16:13 OK - not a stimulating question! But anyway, I've now had a go at just doing it, and in the end it's come out simpler than I'd expected, once I'd realised two things: * No need to check the property name arguments, just try to assign to the properties using them and let the ordinary error handling take care of mistakes. Hence no need to get the property names. (Actually, if the code is in a method and I want to disallow assignment to private properties with this mechanism, it is still fiddly - but an easy way round this is to put the code in an external function.) * Forget about inputParser, do my own parameter/value extraction, and put value checking in the set methods for the properties. But having been through this, it makes me wonder why there isn't an equivalent of hgsetget for value classes. Easy enough, surely, and if it's useful for handle classes isn't it useful for value classes too?
|
Pages: 1 Prev: Problem with matrix in a Simulink bus. Next: cannot build matlab embedded functions in simulink |