What is better option than using 'global' ?
Afficher commentaires plus anciens
Hello all, In GUI, I am using plenty of global variables from which the performance gets influenced . I want to know what are the other alternatives of that and how to implement those programmatically ??
Thank you.
Réponses (2)
The MATLAB documentation covers this quite comprehensively:
Globals are an unreliable way to pass values, and should be avoided. You will find lots of explanations why:
jmgoldba
le 7 Juil 2023
0 votes
"Globals are an unreliable way to pass values, and should be avoided."
Yeah, no. As the wiki link states: "Using globals is perfectly okay ... as long as you are careful about where, why, and how you use them." What's annoying is that Matab lint (or whatever it's called) flags the use of globals regardless.
I use globals as Matlab environment variables as opposed to getenv type, aka operating system environment variables which I limit to instances where the environment variable is useful across programming languages. As such, the globals I use are defined at Matlab startup and accessed as read-only. If Matlab lint wants to flag globals, it should only do so if their value is being set in a function.
13 commentaires
Walter Roberson
le 7 Juil 2023
function val = env_NAME(varargin)
persistent NAME
if nargin > 0
if isempty(NAME)
NAME = varargin{1};
else
error('Attempt to re-set NAME');
end
else
if isempty(NAME)
error('Attempt to get uninitialized NAME');
end
val = NAME;
end
end
now call env_NAME once with a value to initialize NAME; call it without an input to retrieve the value. The code will not permit you to re-initialize NAME and will not permit you to fetch NAME if it has not been initialized.
No global needed. No mlint flags. Accidental re-initialization will cause traceback. Accidental use before initialization will cause traceback.
jmgoldba
le 8 Juil 2023
Um, yeah, no? My globals are typically paths to data directories that I want available to various functions that contain uigetfile calls. So startup.m calls define_globals.m that has something like:
global dataDir someOtherDir
dataDir = 'c:\DataDir';
someOtherDir = 'c:\someOtherDir';
With several (unrelated) functions all containing something like:
global dataDir
[yada yada] = uigetfile(yada, yada, dataDir);
To me that's both simple, readable and not something that should be flagged by mlint. As far as persistent goes, I'm still not clear how it'd work in this instance as it seems to be intimate with the function it's defined in.
Using OS environment variables is probably the best workaround if globals went away, but as I noted earlier there's no need to get the OS involved as this (for now) is a Matlab only thing.
Jesse
Walter Roberson
le 8 Juil 2023
To me that's both simple, readable and not something that should be flagged by mlint.
To me that is code in need of improvement .
Please see http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F for information on better approaches than using global
jmgoldba
le 8 Juil 2023
"To me that is code in need of improvement."
I'm not clear why. The link you provided was for callback functions in a GUI, which isn't applicable in my case. Even so, from the link:
"Functions that do not have the "global myVariable" line in them will not be able to see the variable."
Which is a good thing in my case. Functions should only see the globals I declare in them and not all the globals declared in my define_globals.m above. -Jesse
Jan
le 8 Juil 2023
I've written a tool for clinical decision making, which must work reliably. Users can expand the code by own tools and subroutines. Interferences with other Matlab programs must be actively excluded. The tool has more then 300'000 lines of codes (plus comments!) and exhaustive unit- and integration tests.
If the code uses any gloabl variables, this would be an avoidable vulnerability. There are safer methods to share variables. Although it works in your case currently, it is not more than your hope, that other tools you use simultaneously do not use global variables with the same name oder kill your environment by a clear all or clear globals.
Avoiding globals is recommended by many experiences programmers. Of course you can have a different opinion and as said already they can work in a specific program. E.g. many examples from the FEX destroy the global workspace, but as long as you avoid running foreign codes and have the a perfect overview over your own codes, bugs will not occur. But this will remain fragile. As soon as you share your codes or run other tools in parallel, the program looses the power to control the access of globals.
As a professional programmer I avoid to use porgramming styles, which exclude the sharing of code with other programmers or workgroups by design.
By the way, you can disable MLint warnings individually. Isn't this offered by a right click on the warning?
jmgoldba
le 8 Juil 2023
Let's take a step back. My point is that while global variables can be abused, there are also instances where they are useful and suffer no more vulnerability than other programming aspects. Many things in programming can represent 'vulnerabilities'. My code is a lot of glue between various functions I've downloaded from the internet, or collected from other sources. Something as simple as a function name can represent a vulnerability. On rare occasions I've run into a function name conflct that mlint didn't catch. Heck, I wouldn't mind if mlint warned me about setting/clearing a global - but no. Every. Time. I have a global statement in a function, I get a warning. (Sure I can right-click disable but it shouldn't be necessary.)
My older edition of Code Complete notes that what's considered 'global' can mean different things. In my instance, global variables are used in the manner of OS environment variables while also providing what I consider to be additional advantages that OS environment variables don't have. If you're suggesting that OS environment variables are uniformly a bad thing because, as a type of global variable, their value can be altered by other functions then I guess we'll have to agree to disagree. -Jesse
Walter Roberson
le 9 Juil 2023
If you can easily avoid the problems and the warnings by using a routine similar to env_NAME that I posted earlier, then why wouldn't you do that? It is easily modifyable to support a parameter name so that you would only deal with a single interface function (you might be interested in the speed tests I posted comparing dynamic struct field names against using the new dictionary() class)
jmgoldba
le 9 Juil 2023
"using a routine similar to env_NAME"
I'm not interested in creating multiple essentially duplicate routines (refactoring anyone?) to accomodate each global variable I use just to enforce a read-only condition.
So yeah, sure, with a little more persistence (see what I did there) I could probably create a single routine that allows for something like:
dataDir = getglobal('dataDir');
instead of the current:
global dataDir
Yeah, no, maybe but not likely? The 'global' declaration is simple, convenient and sufficient indication of scope for how this variable should be treated (unless my 2-yr old grandson is at the keyboard). And, for what it's worth, I've occasionally done 'clear all'. But I also like seeing my currently three little globals in the Workspace window after startup as they're a reminder of which paths I've done, gone and set. No matter what prissy old mlint has to say about it ;)
Jesse
Walter Roberson
le 9 Juil 2023
Are you asking for a way to disable that particular warning for your own development environment, or are you asking that Mathworks change mlint for everyone so that it no longer gives that warning ?
jmgoldba
le 9 Juil 2023
Everyone, unless there's a usage (that I'm not aware of) where there's no warning. Car analogy (sort of): Imagine a Porsche always displaying a warning message that you should not drive it because it could dangerous if you exceed the speed limit. Um, okay?
Walter Roberson
le 9 Juil 2023
That isn't going to happen. Using global is almost always poorer code than the alternatives. The code is poor in your situation; you are simply willing to live with it.
Porche analogy: a dash warning that "Driving with the rear trunk open is unsafe!", which you would want disabled for everyone because you (believe) that you know what you are doing when you drive with the rear trunk open.
jmgoldba
le 9 Juil 2023
I know it's not going to happen, but I just wanted to complain. Following your fine analogy, my point is that I'm getting the "Driving" warning. Every. Time. Even when I'm in the parking lot loading groceries. And you guys are telling me it's never, ever safe to open the trunk (throw the groceries in the back seat :)
Mlint warnings have been helpful. They've led to solutions for otherwise hard to debug issues, they even got me off using cvsread and switching to tables. I just don't think they should be used for finger wagging, merely for using a statement provided by language.
Walter Roberson
le 10 Juil 2023
Open an enhancement request with Support. There is a non-zero chance that you will get some sympathy from Support; you certainly are not likely to get any sympathy from the long-time professional programmers who volunteer here.
The long time volunteers here, the people who have helped hundreds or thousands of people, find that the great majority of users do need fingers wagged in their direction about globals -- that globals cause so many problems that they should only be used with reluctance.
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!