Matlab equivalent to calling inside static class - oop

Confer the following code:
classdef highLowGame
methods(Static)
function [wonAmount, noGuesses] = run(gambledAmount)
noGuesses = 'something';
wonAmount = highLowGame.getPayout(gambledAmount, noGuesses); % <---
end
function wonAmount = getPayout(gambledAmount, noGuesses)
wonAmount = 'something';
end
end
end
Is there a way to call a static method of the same class (inside a static) method without having to write the class name? Something like "self.getPayout(...)" - in case the class turns out to get to 500 lines and I want to rename it.

Not an answer to your question directly, but it's worth noting that you can also put "local functions" after the end of your classdef block in your class.m file, and these behave like private static methods, but you do not need to invoke them using the class name. I.e.
% myclass.m
classdef myclass
methods ( Static )
function x = foo()
x = iMyFoo();
end
end
end
function x = iMyFoo()
x = rand();
end
% end of myclass.m

As far as I can tell, "no" with a "but". In general, you can only specify the static method with the class name. However, you can fake your way around the restriction since MATLAB has feval:
classdef testStatic
methods (Static)
function p = getPi() %this is a static method
p = 3.14;
end
end
methods
function self = testStatic()
testStatic.getPi %these are all equivalent
feval(sprintf('%s.getPi',class(self)))
feval(sprintf('%s.getPi',mfilename('class')))
end
end
end
Here, class(self) and mfilename both evaluate to 'testStatic', so the functions above end up evaluating 'testStatic.getPi'.
Or, alteratively, you can write a non-static method, self.callStatic; then always use that. Inside that, just call testStatic.getPi. Then you'll only need to change that one line.

Related

Lua & OO, how to access method from another method?

So if I have an Object and needs to call one method from another within that Object, how do I construct that call?
TestObject = {}
TestObject.__index = TestObject
function TestObject.new()
local self = setmetatable({}, TestObject)
self.value = init
-- a count [integer] of something. Not important what
self.counter = 99
return self
end
function TestObject:getCount()
return self.counter
end
function TestObject:getCountPlus(add_value)
-- HERE HOW SHOULD THIS BE FORMATED??
return self.getCount() + add_value
end
And using this Object would be something like this:
local testObject = TestObject.new()
testObject:getCountPlus(1)
which should result in 100.
The getCount() needs to know what instance it is in. When you write
function TestObject:getCount()
it is same as writing
function TestObject.getCount(self)
(note the colon changed to dot). So calling self.getCount() is like calling getCount with self=nil. Do self:getCount(), which is same as self.getCount(self). This may seem odd: why does interpreter not provide self automatically? It's just the way the language was designed: it only provides self automatically with the : notation.

Calling the actual class in Matlab

Let's say I have this class:
classdef abstractGame
%UNTITLED Summary of this class goes here
% Detailed explanation goes here
properties
end
methods (Abstract, Static)
run(gambledAmount);
end
methods (Static)
function init()
gambledAmount = validNumberInput(abstractGame.getGambleString(), 1, 100, 'helpText', 'round');
end
function str = getGambleString()
str = 'How much do you want to gamble?';
end
end
end
And other classes extends from this class. I would like the child classes to redefine the getGambleString method, and for the init-method to use the one the deepest class defines (instead of abstractGame.[...] I want something like calledClass.[...]).
How should I call that?
Thanks in advance.
That is a static virtual function problem; such a construct, though, doesn't exist even in C++, then I suppose there is no chance to have it in matlab. (virtual function definition.)
Btw, in matlab, non-static methods behave as virtual (as in Java), therefore, if you accept not to use static functions, you can obtain the effect you need.
Proof (simplified code):
classdef abstractGame
function str = init(obj)
str = getGambleString(obj);
end
function str = getGambleString(obj)
str = 'How much do you want to gamble?';
end
end
end
classdef game < abstractGame
methods
function str = getGambleString(obj)
str = 'Hi!';
end
end
end
d = game;
d.init()
ans =
Hi!

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?
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.
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.

Can properties of an object handle returned from a function be used without first assigning to a temporary variable?

I have a function that returns a handle to an instantiated object. Something like:
function handle = GetHandle()
handle = SomeHandleClass();
end
I would like to be able to use the return value like I would if I was writing a program in C:
foo = GetHandle().property;
However, I get an error from MATLAB when it tries to parse that:
??? Undefined variable "GetHandle" or class "GetHandle".
The only way I can get this to work without an error is to use a temporary variable as an intermediate step:
handle = GetHandle();
foo = handle.property;
Is there a simple and elegant solution to this, or is this simply impossible with MATLAB's syntax?
To define static properties, you can use the CONSTANT keyword (thanks, #Nzbuu)
Here's one example from MathWorks (with some errors fixed):
classdef NamedConst
properties (Constant)
R = pi/180;
D = 1/NamedConst.R;
AccCode = '0145968740001110202NPQ';
RN = rand(5);
end
end
Constant properties are accessed as className.propertyName, e.g. NamedConst.R. The values of the properties are set whenever the class is loaded for the first time (after the start of Matlab, or after clear classes). Thus, NamedConst.RN will remain constant throughout a session as long as you don't call clear classes.
Hmm, I don't like to disagree with Jonas and his 21.7k points, but I think you can do this using the hgsetget handle class instead of the normal handle class, and then using the get function.
function handle = GetHandle()
handle = employee();
end
classdef employee < hgsetget
properties
Name = ''
end
methods
function e = employee()
e.Name = 'Ghaul';
end
end
end
Then you can use the get function to get the property:
foo = get(GetHandle,'Name')
foo =
Ghaul
EDIT: It is not excactly like C, but pretty close.
The only way to have a static property in MATLAB is as a constant:
classdef someHandleClass < handle
properties (Constant)
myProperty = 3
end
end
then someHandleClass.myProperty will return 3.

Matlab proxy class issue. (re: dependent properties)

Consider the following Matlab (2009a) classes:
classdef BigDeal < handle
properties
hugeness = magic(2000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.bigDeal.hugeness;
end
end
end
Now consider the following use of them:
Setup:
>> b = BigDeal
b =
BigDeal handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
OneLayer:
>> pb = BigProxy(b)
pb =
BigProxy handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
TwoLayers:
>> ppb = BigProxy(pb)
ppb =
BigProxy handle with no properties.
Methods, Events, Superclasses
Question: Why is my double layered proxy unable to see the hugeness when the single layer can? Dependent properties can be calculated - but does this go only one layer deep for some reason?
Update: See my answer below for workaround.
The problem here is two-fold:
The BigProxy object constructor is designed to accept an input object that has a (non-dependent) hugeness property (like a BigDeal object), which the BigProxy object can then access to compute the value for its own dependent hugeness property.
You are passing a BigProxy object to the BigProxy constructor when you create ppb, and you apparently can't compute a dependent property from another dependent property. For example, this is the error that is thrown when I try to access ppb.hugeness:
??? In class 'BigProxy', the get method for Dependent property 'hugeness'
attempts to access the stored property value. Dependent properties don't
store a value and can't be accessed from their get method.
In other words, the outer BigProxy object tries to compute the value for its dependent hugeness property by accessing the stored value of hugeness for the inner BigProxy object, but there is no stored value since it's a dependent property.
I think the fix for a situation like this would be for the BigProxy constructor to check the type of its input argument to make sure it is a BigDeal object, and throw an error otherwise.
Gnovice provided a good answer to the question "why," thus I awarded him the green check of glory. However, for those wanting a work around, you can do something like this:
classdef BigDeal < handle
properties
hugeness = magic(10000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.getHugeness;
end
end
methods(Access = private)
function value = getHugeness(self)
if isa(self.bigDeal,'BigProxy')
value = self.bigDeal.getHugeness;
else
value = self.bigDeal.hugeness;
end
end
end
end
which will allow you to do the following
>> b = BigDeal;
>> pb = BigProxy(b);
>> ppb = BigProxy(pb);
And each of {b,pb,ppb} will all have the same public methods and properties. The only drawback is that I have had to (unnecessarily IMHO) clutter up BigProxy with a new private getter.