MATLAB: Alternate Constructor Behavior with inputParser

classdefconstructorfactoryinputparsermcosoop

Hi,
I have several classes whose constructors rely on InputParser to collect all the relevant properties. I feed all of the varargin array to the inputParser object. Then I loop over the results struct of the inputParser object and set each field of my class instance equal to the value of the matching field of the struct.
parser.parse(varargin{:});
results = parser.Results;
field_list = fields(results);
for field_index = 1:length(field_list)
field = field_list{field_index};
self.(field) = results.(field);
end
While this works well and allows me to avoid complex syntax in the constructor (not to mention implementation logic), I don't have a good way to emulate multiple-constructor behavior. As I understand it, the standard way to have a non-default constructor is to switch on nargin inside the main constructor. With the inputParser approach, though, that's not reliable (as some inputs are optional, I can't predict nargin with any certainty). I could probably add an optional argument(s), but it's still awkward.
My typical use case is that I need to build an object directly from a string or input file with a syntax defined externally. While in other languages I'd probably use a secondary constructor that takes in either the file path or a string, in MATLAB the best I've come up with is to have a separate function called load_whatever.m that takes in the non-default constructor arguments and calls the default (only) constructor in the usual way. (This is slightly reminiscent of the Factory Design Pattern, but I don't know if the inventors of that one would approve.) Unfortunately, this involves moving class-specific code outside of the class definition file, and is neither object-oriented nor easily configurable.
The only other thing I can think of would be to have a static class method that could act as a secondary constructor. I have a feeling that's a bad idea on more than one count, so I haven't tried that yet.
What's the preferred practice for doing things in single-constructor languages like MATLAB that in multiple-constructor languages would use a second constructor? Is the thing I want to do here even one of those things?
Thanks, Jay

Best Answer

So far, the static method is a leading candidate. Ruby has the same problem http://www.ruby-forum.com/topic/160572#706772
%%classA.m
classdef classA
properties(Access = public)
foo
bar
end
methods(Access = public)
function self = classA(f, b)
self.foo = f;
self.bar = b;
end
end
methods(Access = public, Static)
function result = alt_constructor(some_structure)
result = classA(some_structure.foo_field,some_structure.bar_field);
end
end
end
%%test_classA.m
a = classA(1, 0)
b = classA.alt_constructor(struct('foo_field', 2, 'bar_field', 99))
>> test_classA
a =
classA
Properties:
foo: 1
bar: 0
Methods
b =
classA
Properties:
foo: 2
bar: 99
Methods