TExcelTAD
Home › MATLAB / Octave › Handle Classes & Events

Handle Classes & Events

The classes in Classes (classdef) were value classes: every assignment makes a copy, and methods must return the changed object. Add < handle to the classdef line and you get a handle class instead. A variable of a handle class holds a reference to one object, so every copy of that variable points to the same object, and methods can change it in place.

Value class Handle class
Declared as classdef Point classdef Account < handle
b = a Copies the object Copies the reference: a and b are the same object
Method that changes data obj = deposit(obj, x), caller writes a = a.deposit(5) deposit(obj, x), caller writes a.deposit(5)
Passing to a function The function gets a copy The function can change the caller's object
Typical use Numbers, coordinates, money, small records Things with identity: a file, a device, a simulation, a GUI, a cache

Reference semantics

matlab · try it yourself
a = Account('Ada', 100);
b = a;                    % b refers to the SAME account
b.deposit(50);            % no assignment needed
fprintf('a: %g, b: %g\n', a.Balance, b.Balance);
add_interest(a, 0.1);     % a function can change the caller's object
fprintf('after interest: %g\n', a.Balance);

function add_interest(acct, rate)
acct.deposit(acct.Balance * rate);   % nothing is returned
end

% --- file: Account.m
classdef Account < handle
    properties
        Owner = ''
    end
    properties (SetAccess = private)
        Balance = 0
    end
    methods
        function obj = Account(owner, balance)
            obj.Owner = owner;
            obj.Balance = balance;
        end
        function deposit(obj, amount)
            obj.Balance = obj.Balance + amount;
        end
    end
end
a: 150, b: 150
after interest: 165

Compare this with the value-class Counter of the previous lesson, where forgetting a = a.increment() lost the change. With a handle class there is nothing to forget, but also no protection: any code holding a reference can modify the object.

Shared objects

Because handles are references, several parts of a program can share one object. A typical case is a log or a configuration that many functions write to:

matlab · try it yourself
lg = Logger();
run_step(lg, 'load data');
run_step(lg, 'clean data');
holder.logger = lg;           % stored in a struct: still the same object
holder.logger.add('saved by holder');
fprintf('%d entries:\n', numel(lg.Entries));
fprintf('  %s\n', lg.Entries{:});

function run_step(logger, name)
logger.add(['finished ' name]);
end

% --- file: Logger.m
classdef Logger < handle
    properties (SetAccess = private)
        Entries = {}
    end
    methods
        function add(obj, msg)
            obj.Entries{end+1} = msg;
        end
    end
end
3 entries:
  finished load data
  finished clean data
  saved by holder

Copying a handle object

Since b = a doesn't copy, you need a method that builds a new object when you really want an independent copy. MATLAB provides the mixin class matlab.mixin.Copyable (inherit from it and call copy(a)); Octave 11 doesn't have it, so the portable way is a small copy method of your own:

matlab · try it yourself
a = Settings();
a.Theme = 'dark';
b = a.copy();             % a genuinely new object
b.Theme = 'light';
fprintf('a: %s, b: %s\n', a.Theme, b.Theme);
c = a;                    % just another reference
c.Theme = 'blue';
fprintf('a: %s (changed through c)\n', a.Theme);

% --- file: Settings.m
classdef Settings < handle
    properties
        Theme = 'default'
        FontSize = 12
    end
    methods
        function new = copy(obj)
            new = Settings();
            new.Theme = obj.Theme;
            new.FontSize = obj.FontSize;
        end
    end
end
a: dark, b: light
a: blue (changed through c)

Comparing handles

For handle objects, MATLAB's == asks "the same object?", while isequal asks "same class and equal property values?". Octave 11 does not define == for handle classes yet, but isequal works the same in both:

matlab · try it yourself
a = Settings();
b = Settings();           % a different object with the same values
c = a;
fprintf('isequal(a, b): %d\n', isequal(a, b));
b.FontSize = 14;
fprintf('after change:  %d\n', isequal(a, b));
fprintf('isequal(a, c): %d\n', isequal(a, c));

% --- file: Settings.m
classdef Settings < handle
    properties
        Theme = 'default'
        FontSize = 12
    end
end
isequal(a, b): 1
after change:  0
isequal(a, c): 1
matlab
>> a = Settings; b = Settings; c = a;
>> a == b
ans =
  logical
   0
>> a == c
ans =
  logical
   1

(MATLAB output; in Octave 11, a == b raises "eq method not defined".) To test identity portably, change a property through one variable and check whether the other sees it, or give each object an ID property.

Destructors: the delete method

A handle class may define a method named delete. It runs automatically when the object is destroyed, which happens when the last reference to it disappears (the variable is cleared, overwritten, or goes out of scope when a function returns). It's the right place to close files or release other resources:

matlab · try it yourself
f = TempFile('report');
g = f;
clear f                       % g still refers to the object: nothing happens
disp('f cleared')
clear g                       % last reference gone: delete runs
disp('g cleared')
make_and_forget();
disp('back in the script')

function make_and_forget()
t = TempFile('scratch');      % destroyed when the function returns
end

% --- file: TempFile.m
classdef TempFile < handle
    properties
        Name
    end
    methods
        function obj = TempFile(name)
            obj.Name = name;
            fprintf('open %s\n', name);
        end
        function delete(obj)
            fprintf('close %s\n', obj.Name);
        end
    end
end
open report
f cleared
close report
g cleared
open scratch
close scratch
back in the script

Avoid calling delete(obj) yourself in code meant for both programs: MATLAB then invalidates every reference to the object (isvalid(obj) becomes false), while Octave 11 has no isvalid for classdef objects and runs the destructor a second time when the variable is cleared.

Events and listeners in MATLAB

Handle classes in MATLAB can declare events. Other code subscribes with addlistener, and the class announces the event with notify, which calls every listener's callback with the source object and event data:

matlab
classdef Thermostat < handle
    properties
        Temp = 20
    end
    events
        TooHot
    end
    methods
        function setTemp(obj, t)
            obj.Temp = t;
            if t > 30
                notify(obj, 'TooHot');
            end
        end
    end
end
matlab
>> th = Thermostat;
>> lh = addlistener(th, 'TooHot', @(src, evt) fprintf('Alarm: %g degrees!\n', src.Temp));
>> th.setTemp(25)
>> th.setTemp(34)
Alarm: 34 degrees!
>> delete(lh)          % stop listening
>> th.setTemp(40)

(MATLAB output.) MATLAB can also fire events automatically when a property changes: mark the property SetObservable and listen for PostSet. Octave 11 accepts an events block but has no notify or addlistener.

Portable events

The same design works in both programs if the class keeps its own list of callbacks (the pattern from Function Handles & Callbacks). Because the class is a handle, the list lives inside the one shared object:

matlab · try it yourself
th = Thermostat();
id = th.onTooHot(@(src) fprintf('Alarm: %g degrees!\n', src.Temp));
th.onTooHot(@(src) disp('  -> fan switched on'));
th.setTemp(25);
th.setTemp(34);
th.removeListener(id);
th.setTemp(40);

% --- file: Thermostat.m
classdef Thermostat < handle
    properties
        Temp = 20
    end
    properties (Access = private)
        Listeners = {}
    end
    methods
        function id = onTooHot(obj, callback)
            obj.Listeners{end+1} = callback;
            id = numel(obj.Listeners);
        end
        function removeListener(obj, id)
            obj.Listeners{id} = [];          % keep positions, so other ids stay valid
        end
        function setTemp(obj, t)
            obj.Temp = t;
            if t > 30
                obj.fire();
            end
        end
    end
    methods (Access = private)
        function fire(obj)
            for k = 1:numel(obj.Listeners)
                cb = obj.Listeners{k};
                if ~isempty(cb)
                    cb(obj);
                end
            end
        end
    end
end
Alarm: 34 degrees!
  -> fan switched on
  -> fan switched on

Choosing value or handle

  • Choose a value class when two objects with the same data are interchangeable (a point, a date, an amount of money). They're simpler to reason about: no other code can change your copy.
  • Choose a handle class when an object has an identity and a lifetime: a connection, a running simulation, a cache, a GUI component, or anything that needs events or a destructor.
  • In a handle class, methods that change the object don't return it; in a value class, they must.

Learn more: Inheritance & Operator Overloading builds class hierarchies from both kinds; Local & Nested Functions shows a lighter way to keep shared state.

Test yourself

a is a handle object. After b = a; b.Value = 5;, what is a.Value?

  1. Its old value
  2. 5
  3. Empty
  4. An error

When does a handle object's delete method run automatically?

  1. Every time a variable referring to it is cleared
  2. When the last reference to it disappears
  3. Only when you call delete yourself
  4. When MATLAB exits only

Which MATLAB function subscribes a callback to an event of a handle object?

  1. notify
  2. addlistener
  3. events
  4. listen