1
votes

How can I avoid repeating a long tedious package name in matlab classes in the following cases:

  • When specifying the Superclass, e.g. classdef Class < tediouspkgname.Superclass
  • When calling the superclass constructor, e.g. obj = [email protected](...).
  • When calling superclass methods, e.g. val = [email protected](...).

I'm looking for an equivalent of matlabs import statement, which is not usable in these cases unfortunately.


MWE:

Lets have a folder called +tediouspkgname/ in our Matlab path. So Matlab recognizes there's a package called tediouspkgname.

Lets have a Class ExampleClass which is saved in the file +tediouspkgname/ExampleClass.m:

classdef ExampleClass
    properties
        p
    end
    methods
        function obj = ExampleClass(p)
            obj.p = p;
        end
        function print(obj)
            fprintf('p=%s\n',obj.p);
        end
    end
end

Let there be another Class, derived from ExampleClass, living in the file +tediouspkgname/DerivedClass.m:

classdef DerivedClass < tediouspkgname.ExampleClass
    methods
        function obj = DerivedClass(p)
            obj = [email protected](p);
        end
        function print(obj)
            [email protected](obj);
            fprintf('--Derived.\n');
        end
    end
end

I want the following commands to work without errors while mentioning tediouspkgname. as little as possible:

e = tediouspkgname.ExampleClass('Hello');
e.print();

o = tediouspkgname.DerivedClass('World');
o.print();

In particular, this definition of DerivedClass gives me the error ExampleClass is not a valid base class:

classdef DerivedClass < tediouspkgname.ExampleClass
    methods
        function obj = DerivedClass(p)
            obj = [email protected](p);
        end
        function print(obj)
            import tediouspkgname.ExampleClass
            print@ExampleClass(obj);
            fprintf('--Derived.\n');
        end
    end
end
1
You must specify the fully qualified name which includes the package name. The solution is to not make your package name be as long as tedious. - Suever

1 Answers

0
votes

You have two examples at the command line:

e = tediouspkgname.ExampleClass('Hello');
e.print();

o = tediouspkgname.DerivedClass('World');
o.print();

For these cases, you can use import at the command line:

import tediouspkgname.*
e = ExampleClass('Hello');
e.print();

o = DerivedClass('World');
o.print();

and it should work fine.

For the other cases you have (in the class definition line, and when calling a superclass method), you need to use the fully qualified name including the package.

I dislike this aspect of the MATLAB OO system. It's not just that it's tedious to write out the fully qualified name; it means that if you change the name of your package, or move a class from one package to another, you have to manually go through your whole codebase in order to find-and-replace one package name for another.