7

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

But if I have also other classes (Minimum, Mean and so on) i'd like to choose somewhere in the beginning wich type is used and after that using some object of abstract class, without saying which exactly class it is. In this case I can't use static, isn't it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.