Difference of handle and values classes
The MathWorks provide some information on which to be used for which purpose in their help and also in their PDF documentation. I've also found this article from the Yagtom Project (originally by Matt Dunham) to be a great introduction to OOP in MATLAB.
In the help this was explained as follows (emphasis mine):
MATLAB support two kinds of classes — handle classes and value classes. The kind of class you use depends on the desired behavior of the class instances and what features you want to use.
Use a handle class when you want to create a reference to the data contained in an object of the class, and do not want copies of the object to make copies of the object data. For example, use a handle class to implement an object that contains information for a phone book entry. Multiple application programs can access a particular phone book entry, but there can be only one set of underlying data.
The reference behavior of handles enables these classes to support features like events, listeners, and dynamic properties.
Use value classes to represent entities that do not need to be unique, like numeric values. For example, use a value class to implement a polynomial data type. You can copy
In the article by Matt Dunham, another good point is made to distinguish both types of classes:
We previously mentioned that objects in Matlab are, (by default) passed by value, meaning that full copies are passed back and forth in method calls. Matlab graphics objects, however, are passed by reference, (via handles). If we subclass the built in handle class [...] then objects of our class will be passed by reference too, not value.
I personally tend to use handle classes to get some of the syntax I'm used to with Java:
for a handle class, you can have the object store all information, such that you can have operations like sort(a)
(or a.sort()
) be performed in place.
For value classes the equivalent of this is a = sort(a)
(or a = a.sort()
). For operators the first syntax makes no sense at all, but the second is obviously in general use: e.g. a = a + b
(this is equivalent to a = plus(a,b)
and a = a.plus(b)
).
- If the main concern of your class is to store (numeric) values of some kind and to be able to perform operations, the value class is most likely the way to go.
- If you want to store a state, group related values, connect different objects together (linked lists, graphs, ...), the handle class might be the way to go.
Or at least, that's what I tend to use to make the distinction.