MATLAB:有条件地定义get / set类方法

时间:2017-08-16 03:04:43

标签: matlab oop

当我使用某些类型的结构时,我创建了一些MATLAB类来进行一些错误检查。这可以通过防止代码中的错误来缩短开发时间,但会显着减慢执行时间。

解决这个问题的一种方法是注释掉类中的set方法。是否可以通过编程方式执行此操作?例如,如果构造函数中的参数为true,则仅定义这些方法。

classdef MWE
    %MWE     Minimum working example

    properties
        A
        B
        C
    end

    methods
        function obj = MWE(A, B, C)
            if nargin ~= 3
                error('A, B and C must all be provided.');
            end

            obj.A = A;
            obj.B = B;
            obj.C = C;
        end

%         function obj = set.A(obj, value)
%             validate(obj, value, 'A');
%             obj.A = value;
%         end
%                 
%         function obj = set.B(obj, value)
%             validate(obj, value, 'B');
%             obj.B = value;
%         end
%         
%         function obj = set.C(obj, value)
%             validate(obj, value, 'C');
%             obj.C = value;
%         end

    end

    methods (Access = private)
        function validate(obj, value, name)
            % Code here
        end 
    end
end

1 个答案:

答案 0 :(得分:0)

  

是否可以通过编程方式执行此操作?例如,如果构造函数中的参数为true,则仅定义这些方法。

经过一番讨论后,我发现有不同的方式来查看你的问题。事实上,可能是你不能按照某些人的解释做你所要求的。但是,有两种情况可能就足够了。

  • 案例1

    您有计算密集型或其他耗时的方法,您可以在开发设置中执行某些错误检查,但希望在生产环境中关闭。并且,在实例化类时会发生这些检查。

将这些方法放在从构造函数调用的包装函数中。

这是一个例子

classdef classFoo
   properties(Access=private)
       fbar;
   end
   methods
       function this = classFoo(arg1, argN, debugMode)  
           if(nargin>2 && debugMode)
               if(~this.verifyStuff(arg1, argN))
                   throw(MException('classFoo:ConstructFailure','Could not verify'));
               else
                    this.fbar = timeConsumingFunction();
               end
           else
               this.fbar = 42; % defaultValue;
           end           
           % continue construction

       end
       function didVerify = verifyStuff(this, varargin)
           % complex code
           didVerify = randi(2)-1;  % 50/50
       end
   end
end

然后在创建对象时,您可以选择将调试模式标志传递为true,如下所示:

a=classFoo(1,2,true)

或假,如下:

a=classFoo(1,2,false)

或根本没有,这与假案例相同,如下:

a=classFoo(1,2)
  • 案例2

    根据您的开发环境,您有两个不同版本的get / set方法。

添加私有成员参数(例如isDebugging)并在构建时设置它。现在,您可以使用简单的if / else处理不同的情况,而不是在get和set方法中注释掉代码,而是根据调试状态进行判断:

classdef classFoo
   properties(Access=private)
       fbar;
       isDebugging;
   end
   methods
       function this = classFoo(debugMode)  
           if(nargin<1 || ~islogical(debugMode))
               debugMode = false;
           end
           this.isDebugging = debugMode;
        end
        function setfbar(this, fIn)
             if(this.isDebugging)
                 this.fbar = timeConsumingFunction(fIn);
             else
               this.fbar = fIn; % defaultValue;
           end           
        end
   end
end
相关问题