Search code examples
matlabclasspathsubdirectorycode-organization

In matlab, is it possible to put methods of classes organised in folders in subdirectories/subfolders?


I am new to the option of organising your classes in class folders in matlab. In terms of readability, my code benefits from putting methods of the class in separate files, because oftentimes the methods are quite lengthy. Now, I believe it would be even nicer, if I could further organise my code; I'd like to create subdirectories within the class folder. The structure I'm looking for is like this (just an example):

@Foo/
├──Foo.m/
│
├──staticMethods/
│  ├──staticMethod1.m
│  ├──staticMethod2.m
│
├──privateMethods/
│  ├──privateMethod1.m

However, I can't seem to find anything about subfoldering in class folders, nor does it work when I try it, because matlab seems not to find the folders staticMethods and privateMethods.

Therefore my question: in matlab class folders, is it possible to create subfolders with methods in them?


Solution

  • No, this is not possible. Only the directory Foo itself is searched for M-files, its subdirectories are not. The exception is a subdirectory called private, which can contain M-file functions only visible to the M-files within its parent directory (documentation).

    Public methods all have to be directly in the Foo directory. Private methods can be in the private subdirectory. Static methods must be defined within the classdef file.

    In general, your directory structure can look like this:

    @Foo/
    ├──Foo.m
    ├──A.m
    ├──B.m
    ├──private/
    │  ├──X.m
    │  ├──Y.m
    

    Foo.m must contain the classdef definition for class Foo (or, if you go with a pre-classdef class, just its constructor method, though this is not recommended). The classdef definition contains all static methods, setters and getters, and any methods that need special access permissions. Functions A and B are public methods of Foo. X and Y are functions accessible to any code within Foo.m, A.m, B.m, X.m and Y.m.


    To structure your code, you can take longer functions and split them out as private sub-functions, leaving not much more than its declaration in the classdef:

    classdef ClassName
       properties
          ...
       end
       methods
          function obj = C(obj,vararg)
             obj = C_internal(obj,vararg{:});
          end
       end
    

    and in a file private/C_internal.m:

    function obj = C_internal(obj,arg2,arg3,arg4,...)
       ...
    end
    

    (Note the use of vararg, which prevents repeating the argument list, duplicated argument lists are a good way of introducing bugs.)

    The only issue here is that the documentation still has to sit in Foo.m. I personally don't like separating code from documentation, and prefer keeping them together in the same file.