I'm writing a MATLAB application which has many functions spread over different files. I have a logger, which is a struct with a function pointer, and I use it to log information for the user to see (that is, which function is currently executing, calculation results, etc.). The reason I use a struct for my logger and not simply fprintf()
is that I could easily replace it with an XML logger, HTML logger, etc. in the future.
Since my code is composed of many functions calling each other, I declared my logger struct as global, so I don't have to pass it to all my many functions. However, everywhere I look I see that global variables are evil incarnate in MATLAB and will slow my program down considerably.
Is there a way to have variables available across files without necessarily passing them as input parameters, and without suffering from severe performance penalty?
You can also use persistent keyword inside a file, and allocate the logger there.
It is similar in some ways to the static keyword in C++. It is also an implementation of the Singleton pattern.
function CallLogger(st)
persistent logger;
if isempty(logger)
%Allocate new logger
end
logger.disp(st);
end
It is better than global because
1. No one can destroy your logger without your knowledge.
2. No one even knows about this object, because it is limited to the function scope
By the way, I don't agree that global has a performance issue. It is just not a good practice, in terms of Software Engineering.
Better than invoking persistent variables in a function (which, for example, won't be saved if you save and then reload your workspace) would be to move from function + struct to object: that is, you should look into MATLAB's object oriented programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With