Suppose we have Check.m:
classdef Check < handle
methods (Static)
function doStuff()
if isCalledFromAssertSubclass
% do this stuff only if called as Assert.doStuff(), not if called as Check.doStuff()
end
% do other stuff
end
end
end
and Assert.m:
classdef Assert < Check
% nop
end
As written in the comment, I would like to have that Check.doStuff()
executes only the "do other stuff" line and that Assert.doStuff()
executes the if isCalledFromAssertSubclass
block as well.
I want to use static methods, so that I don't neet to create an Assert object whenever I need an assert. Using a global assert object is also very ugly and needs a global assert
line in each function I want to use an assert. Likewise for checks.
So there are two problems:
class(obj)
or any other non-static class property or function.dbstack
is not inheritance aware and always returns Check
as calling class, also for Assert.doStuff
.I did find a working solution, which uses a combination of dbstack
and dbtype
to read the line where the call came from, i.e. the line where it says Assert.doStuff()
. However it involves two debug functions which probably should not be used in productive code and more importent, dbtype is very slow (in my case, 30 our of 70 seconds!).
I could use a package instead (directory +Check
with function files in there) and create a symlink +Assert -> +Check
. Then I could check the file name, but that's a) not portable, b) quite ugly and c) also somewhat slow (I suppose).
Is there any faster method for this?
Why not overload the static method for Assert
, and have it call the parent's method when it's done? This is the normal way of using inheritance: you don't want the parent, Check
, to know anything about its child, Assert
.
This is what it would look like:
classdef Assert < Check
methods (Static)
function doStuff()
% do some stuff
Check.doStuff()
end
end
end
As @Wolfie suggests in a comment, the above works as long as Check.doStuff
is not sealed. A sealed method cannot be overloaded. See the documentation.