MATLAB: Namespace management for packages+sub-packages

classdefnamespacesooppackages

Hello all, I have a question regarding namespace management for a series of packages and sub-packages.
Let us create a folder structure like this
.\+Behaviors\+Quacking\quackBehavior.m
.\+Behaviors\+Quacking\Quack.m
.\+Behaviors\+Quacking\MuteQuack.m
With the interface class
classdef (Abstract) quackBehavior < handle
methods (Abstract)
perform(obj)
end
end
And the concrete subclasses
classdef Quack < quackBehavior
methods
function perform(~)
disp('Quack!')
end
end
end
and
classdef muteQuack < quackBehavior
methods
function perform(~)
disp('<<silence>>')
end
end
end
All of this is to implement something like
duck.vocalization = Behaviors.Quacking.Quack;
perform(duck.vocalization)
Ok, the issue is that due to the package namespace, both of the concrete subclasses throw errors of the form: The class 'quackBehavior' contains a parse error, cannot be found on MATLAB's search path, or is shadowed by another file with the same name.
Now, I know how to practically fix this, I need to change Quack.m to:
classdef Quack < Behaviors.Quacking.quackBehavior
methods
function perform(~)
disp('Quack!')
end
end
end
and similarly for muteQuack.m. This works, but seems to violate the desired behavior in two ways:
  • Quack.m is in the same +Quacking package as quackBehavior.m; why does it need to know the full package name? I know that this is also a requirement of static methods, since you aren't accessing an object of the class. Still, it strikes me as defeating the purpose of packaging the classes in the first place. It might be better from a code standpoint to leave everything in one massive root-folder in Matlab's path, but then I lose all of the control for overloading functions. What if I also had a duck species named 'Quack', and needed a seperate classdef ./+Ducks/Quack.m, so that duck = Ducks.Quack; duck.vocalization = Behaviors.Quacking.Quack. There does not seem to be any namespace ambiguity if I do not include the full package path in the classdef, as the behaviors are encapsulated in their own packages, as the ducks are in theirs.
  • If I later enclose +Behaviors in another package, e.g. ./+WaterfowlToolkit/+Behaviors/… then I have to manually modify all of the classdef lines in every class in every package below +WaterFowlToolkit. This strikes me as a minefield for code maintainence and reuse.
So, is there a better way of doing this that takes care of the above concerns? Is there a trick using import, e.g. import +WaterfowlToolkit/*, or something in that vein that would give the deisred behavior; the ability to nest packages as above to maintain some organizational sanity in large code sets and maintain overload/namespace control without needing to define the full package heirarchy in every classdef?

Best Answer

If you figure out let us know... this has been a major complaint for 4+ years and no response yet from Mathworks. It makes packages useless.