Lex
Lex

Reputation: 169

Using abstract classes in Matlab (without properties)

Let we have one abstract class:

classdef ACalculation < handle

    methods (Abstract)
        [result] = calculate (this, data);

        plot (this, data, limX, limY);
    end

end

And some other classes that implements ACalculation

classdef Maximum < ACalculation

    methods
        function [result] = calculate (this, data)
            %...
        end

        function plot (this, data, limX, limY)
            %...
        end
end

To functions of implementation class i give all needed information, so i don't need any properties. So it looks like I need static classes. But if I have static classes I have a problem with calling this functions. I'd like to do something like that:

criteria = Maximum();
%......
result = criteria.calculate(data);

Is it bad way to use inheritance? Should I ignore matlab advices to change functions to static? What else could I do here?

Upvotes: 7

Views: 4025

Answers (2)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

I think that in this case, static interface implementation is quite a good pattern. Define your classes in the following way:

classdef ACalculation < handle

    methods (Abstract,Public,Static)
        [result] = calculate (data);    
        plot (data, limX, limY);
    end

end

classdef Maximum < ACalculation

    methods (Public,Static)
        function [result] = calculate (data)
            %...
        end

        function plot (data, limX, limY)
            %...
        end
end

Then, you can write a function that expects an ACalculation type:

 function foo(acalc,data)
      assert(isa(acalc,'ACalculation'));
      acalc.calculate(data);
      acalc.plot(data,[100 200]);
 end

Then create a Maximum empty instance and pass it to foo:

 foo ( Maximum.empty(0), [1 2 3]);

If you want to change the calculation method, call

 foo ( Minimum.empty(0), [1 2 3]);

When you say that such a pattern will not work, you are thinking like Java/C#/C++ developer. But unlike in C++ where static and virtual keyword cannot coexist, Matlab has no such limitation, because everything is done at runtime, and an "instance" can be empty or an array of n elements.

Upvotes: 5

Sam Roberts
Sam Roberts

Reputation: 24127

If calculate is a static method of Maximum‘, you would use ‘result = Maximum.calculate(data) to call it, without instantiating to criteria.

It's not (necessarily) a bad way to use inheritance, or bad advice from MATLAB.

Upvotes: 0

Related Questions