Kristina Kossarev
Kristina Kossarev

Reputation: 21

How do I write a common set method for multiple properties in MATLAB

I work within a project which has several classes which define properties that use essentially the same set method. To make the code more readable, I want to implement a commonSetter method. The overall goal is to include this commonSetter method in the superclass, so that all the classes could use it.

The question was already posted here, but unfortunately, the answer is not working. I changed the code to the following, but get the error: Maximum recursion limit of 500 reached.

classdef MyClass

properties
    A
    B
end

methods
    
    function mc = MyClass(a,b) % Constructor
        mc.A = a;
        mc.B = b;
    end
    
    function mc = set.A(mc, value) % setter for A
        mc = mc.commonSetter(value, 'A');
    end
    
    function mc = set.B(mc, value) % setter for B
        mc = mc.commonSetter(value, 'B');
    end
    
    
end

methods(Access = protected)
    
    function mc = commonSetter(mc, value, property)
        % do some stuff
        disp('Made it into the commonSetter!')
        mc.(property) = value;
    end
end 
end

So far I know that there is an infinite loop where mc.(property) = value; calls set.A (or set.B), which in turn calls commonSetter. In my post @ MathWorks the following was suggested:

To break that loop I guess you should look at builtin() and subsasgn(). Maybe Overriding subsref and subsasgn - effect on private properties can be of some help.

Currently, I have troubles realizing the suggestions and additionally not very comfortable to overwrite subsasgn() as I'm not sure how it will affect the overall project. I would like to know, if someone has other ideas or knows how to overwrite subsasgn() safely.

Upvotes: 2

Views: 778

Answers (1)

rinkert
rinkert

Reputation: 6863

To solve the recursion error, you could just let the commonSetter method output the new value instead of the object.

classdef MyClass

    properties
        A
        B
    end

    methods

        function mc = MyClass(a, b)% Constructor
            mc.A = a;
            mc.B = b;
        end

        function mc = set.A(mc, value)% setter for A
            mc.A = mc.commonSetter(value, 'A'); % update mc.A
        end

        function mc = set.B(mc, value)% setter for B
            mc.B = mc.commonSetter(value, 'B');
        end

    end

    methods (Access = protected)

        function new_value = commonSetter(mc, value, property) % only return the new value
            % do some stuff
            disp('Made it into the commonSetter!')
            if value > 5
                new_value = -10;
            else
                new_value = value;
            end
        end
    end
end

Upvotes: 2

Related Questions