Search code examples
matlab

Handle Class to avoid copies - problematic?


classdef DataContainer < handle
    properties
        d
    end
end
my_cells = DataContainer();
my_cells.d = cell(1, 100);
func(my_cells)
updated_data = my_cells.d{1:5};

Issues with such an approach? Seems too good. I'm only concerned with speed (and memory only if garbage collection fails).

The context is passing a data structure around to helper functions, without having to rewrite everything into a class. I'm aware there's property access overhead - i.e. my_cells.d{1} is slower than d{1} by itself would've been - but suppose that's acceptable.

Example issue, I've heard that once .m files are compiled into an optimized format, we want classes with fixed data types. (I imagine bypassing this by pre-initializing all possible containers - don't know if valid, but maybe separate topic.)


Solution

  • The context is passing a data structure around to helper functions, without having to rewrite everything into a class.

    Just use a struct. This is what structs are designed to do, and they do it well. It will be faster, it will make more sense to the reader, and you won’t have that extra file defining a useless class.

    If you need to modify the struct within the function, then the struct is both an input and an output argument.

    Handle classes are meant to own resources that cannot be copied (or would be too expensive to copy). That is their purpose. For example MATLAB’s graphics: each window and every other one of the graphical elements on the screen are owned by a handle object. Each object corresponds to one of those objects. Copying the object would duplicate the graphical element on the screen, which you cannot do. Deleting the object deletes the graphical element on the screen. If your object has a similar function (maybe it owns an open file, or a network connection) then a handle class is the right way to define that object.

    MATLAB’s regular syntax makes input arguments to a function immutable. When you call func(a), you expect a will not change. Handle classes break this expectation, and therefore must be used with caution. Using them to break the expectation is just a terrible idea, you are making your code hard to read.

    99% of examples in the docs that use a class make it into a handle class. This is wrong, and has normalized the use of handle classes for purposes where a value class is much more appropriate. I am certain that it was Java-trained programmers with little MATLAB experience that wrote those examples. And it makes me sad to read them.