简体   繁体   中英

Best alternative to MATLAB's global variables

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.

比调用函数中的持久变量(例如,如果保存然后重新加载工作区将不会保存)更好的是从函数+结构转移到对象:也就是说,你应该研究MATLAB的面向对象编程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM