I want to update the definition of my class with new behavior in a non backward compatible way, but I still want to be able to use old instances of the class and have them use the old class definition (i.e. with the old behavior).
Suppose I have a class named MyClass (defined as follows) and I have some instances of MyClass saved to a MAT-file.
% MyClass.m
classdef MyClass < handle properties value (1,1) double end methods function obj = MyClass() obj.value = 0; end function v = getValue(obj) v = obj.value; end function v = add(obj,a,b) v = a + b; obj.value = v; end endend
Now suppose I want to update the definition of MyClass to be the following, which changes parts of the behavior of MyClass.
% MyClass.mclassdef MyClass < handle properties value (1,1) double end methods function obj = MyClass() obj.value = 100; end function v = getValue(obj) v = obj.value; end function v = add(obj,a,b) v = a - b; obj.value = v; end endend
Clearly, this second version of MyClass is not backward compatible, since it will break code that depends on the old behavior. For example, the 'add' method now subtracts its inputs as opposed to adding them.
How can I update the definition of MyClass in such a way that, when I load the old instances of MyClass from my MAT-file, they use the old class definition with the old behavior?
Best Answer