matlaboopmatlab-class

matlab oop - how could i handle input of constructor?


I have a handle class, i.e mclass below, which should be constructed inside another function with corresponding input argument. However, i want to check the input argument of the class constructor inside the constructor of wherever in the class itself, and prevent new object handle being created if input is not desired type.

classdef mclass < handle
    properties
        val
    end
    properties (Dependent)
        sval
    end
    methods
        function obj = mclass(varargin)
            if nargin == 1
                if isnumeric(varargin{1}) && varargin{1} > 0
                    obj.val = varargin{1};
                else
                    errordlg('Invalid input', 'Constructor', 'modal');
                end
            else
                errordlg('No input', 'Constructor', 'modal');
            end
        end
        function s = get.sval(obj)
            s = sqrt(obj.val);
        end
    end
end

However, after calling m = mclass; or m = mclass(0); from Command Window, together with the error dialog, variable m is still created in the Workspace. How can I prevent m being created?

Of course I can check for the input inside my other functions before calling constructor, but is there anyway to make it a "self-check" characteristic of the class?


Solution

  • errordlg does not stop program execution. It only displays the dialog. To stop your program additionally you need to issue a call to error. You can combine both and use the following lines which will stop object creation when you issue an error.

    function obj = mclass(varargin)
        if nargin == 1
            if isnumeric(varargin{1}) && varargin{1} > 0
                obj.val = varargin{1};
            else
                errordlg('Invalid input', 'Constructor', 'modal');
                error('Invalid input for Constructor of mclass');
            end
        else
            errordlg('No input', 'Constructor', 'modal');
            error('No input for Constructor of mclass');
        end
    end