systematic: Do not use global, don't use eval
Afficher commentaires plus anciens
I don't agree with systematic: don't use eval, or global or ... and my question is why those command are still not removed by Mathworks? We can explain the risk of using those functions. For a begginers who make small programs, I don't see any problems to use such commands. Offcourse, We recommand other alternatives, but I find it is an exaggeration to say, every time it is very bad. It looks like a censorship. I am still using global and eval function and never had a problem.
2 commentaires
A very important question! The answers are unequivocal.
I find 16 votes for answers currently. But can the answers be more important than the question? When this question is not made prominent by voting, the forum contributors have to answer dozens or hundreds of EVAL question in the future also...
Jan
le 30 Déc 2012
@Azzi: I hesitate to accept an answer in this thread. But I think Matt Fig's answer earns this. And the other answers are pointing in the same direction.
Réponse acceptée
Plus de réponses (8)
Jason Ross
le 26 Oct 2012
7 votes
I have a lot of tools in my garage. Some are very sharp, very pointy and I use them with extreme care because they are the best tool for the job. If I didn't have them available to me, I couldn't do certain jobs.
The avoidance of global variables is not something unique to MATLAB programming. It's been considered a "best practice" in some form or another for other languages I've used, as well.
3 commentaires
Sean de Wolski
le 26 Oct 2012
Jason, I like that analogy and on that note: I have a bunch of tools in my porch (no garage :( ) and if I am looking to cut down a tree I will use the chain saw not the oil filter remover.
Jason Ross
le 26 Oct 2012
The chain saw is a tool that's a great example of extremely useful and extremely dangerous. Not only is the tool itself dangerous, but it also has the capability to change the environment in less than predictable ways that can be very dangerous or lethal. Kind of like eval and global variables!
Sean de Wolski
le 26 Oct 2012
On that note, I need to put a new chain on the saw before Sandy comes through...
Sean de Wolski
le 26 Oct 2012
5 votes
I disagree that it's fine for beginners to use eval and global. These are of course the easy way out, but you never get better at anything by taking the easy way out and you don't learn how to do things in the best matter.
Thus I would say it's especially important that beginners specifically don't use eval, globals etc. since they are not seasoned enough to know the dangers of these tools and the fact that there are better things they could learn.
1 commentaire
+1 yep. Those beginners (at my work) who use these constructs end up calling me to come fix their mess a few months down the road. That is when I have to come and teach them how to do it the right way.... Then for some reason they do not call me anymore with such questions! ;-)
EVAL is evil. GLOBAL is evil.
Both increase the complexity of programs and there is always a smarter, safer and more readable method. Daniel's example of overloading display is exotic - I agree that exotic problems can require exotic solutions.
I've read and answered too many questions in different Matlab forums concerning these two commands. Therefore especially the experiences of beginners have shown, that these commands cause more problems than they solve.
In addition I've seen the drawback of EVAL and GLOBAL when a program is successfully working at first, and then expanded in the future. It is nearly impossible to find the source of errors, if any of the subfunctions set a wrong value to a global variable. Debuggung gets a pure horror.
It is very nice and fine, that you, Azzi, never had troubles with these commands. Perhaps such problems appear suddenly, when you try to join your programs with the code of others. Or if your programs exceed the magic limit of 100'000 lines, which is a maximum a human can keep the overview without using special techniques for code abstraction (OOP, a clear and standardize documentation, unit-testing, strict programming conventions).
So it is ok, when a program with 1000 lines runs fine with bad programming methods. And when problems occur and you ask in a forum, you will and must get the valuable advice to avoid bad programming methods. This is not a censorship, this is sharing experience.
4 commentaires
Matt Fig
le 26 Oct 2012
"This is not a censorship, this is sharing experience."
Well said. Why lead a new user to learn the hard way when we can tap the combined experience of others, especially when that experience points in a common direction?
Sean de Wolski
le 26 Oct 2012
Censorship would be setting up a script to open each Answers question and do a regexprep on all uncommented calls to global or eval in code and having it traverse all valid questions...
It could even replace eval with a link to this thread. I don't think this is on Randy's agenda though ;)
I learned it the hard way also: When I started programming in Matlab in a greater environment, I had one global variable called G_, which stored all values and flags which needed a global access, e.g. the current debug level (degree of verbosity) or a flag if uninitialized data are set to NaN or Inf. Only one function SetGlobal was allowed to modify values in this struct, such that I had a chance to trace and debug all modifications.
But then the programming team has grown and my strategy has been adapted by some co-workers partially: Whenever they thought that changes of G_ are not so important, temporarily only and concern their own parts of the framework only, they wrote directly to the global variable. After some of the colleages have left the team later, the need aroses, that some of their GUIs are opened multiple times. Of course this caused collisions in G_ and the debuggiung was too cruel.
The solution was trivial: No globals, even not with good intentions. If I really need a shared flag, and this is a very rare case, it is encapsulated in a PERSISTENT variable such that users are forced to use the standard interface.
Sean de Wolski
le 26 Oct 2012
Or as a function that you call that returns a value. Like pi().
In small programs it's not a problem. If you are the only one that will be ever using your code, it should not be a problem. It will however become a problem a few years (or months) down the road when you are trying to understand what you did.
It is a bad idea to recommend globals to new programmers, as they will grow used to using them. Which will cause fellow programmers a world of headaches once they start working in large projects.
In a perfect world, they are not bad and can be useful. In a perfect world I would always remember what function dothis actually does and where all its dependencies are located. As it turns out, I have a hard time remembering what I had for breakfast. It is a matter of clarity and futureproofing.
1 commentaire
Jan
le 26 Oct 2012
EVAL is a problem even in small programs:
function myTest
disp(sin(1));
eval('sin = 2;')
disp(sin(1));
Now you can get different results when you run this in debug or non-debug mode.
Daniel Shub
le 26 Oct 2012
3 votes
There are certain things that cannot be done without EVAL (or meta programming). In general, these are hacky type things. For example in this question of mine. Similarly, EVALIN and ASSIGNIN can let you do things that cannot be done any other way.
The large majority of the uses of EVAL on Answers and CSSM can be easily avoided. It is such a large majority that it is not an exaggeration to say "never." Even if you avoid the maintenance and debugging nightmares that using EVAL can cause, you still effectively eliminate the JIT and decrease MATLAB's performance significantly.
Global variables also allow you to do things that difficult without them. In particular I find global variables sometimes useful for communicating between GUIs, although now that figures and the "root object" have "application data", I often make my global variables that way. To me the two methods are essentially the same. But again, in the large majority of cases there are better ways than globals.
4 commentaires
Walter Roberson
le 26 Oct 2012
Myself, I am not convinced that the guidata() system is significantly better than globals. A touch better in some ways, but also pretty clumsy and the source of a lot of mistakes.
Sean de Wolski
le 26 Oct 2012
Two reasons guidata/appdata are better:
- guidata (or app data) for a hidden handle, i.e. a handle whose 'HandleVisibility' is 'off' can protect you from external interference that globals could be affected by.
- When the object is destroyed, all of the information is also destroyed and thus not lingering to cause headaches later.
Daniel Shub
le 26 Oct 2012
I was trying to say I think appdata variables are global variable, but as Sean notes, a little better.
Jan
le 26 Oct 2012
ApplicationData are global's in practice, when they are stored in the root object.
Here's a fairly simple scenario where EVAL seemed inevitable, though perhaps I'm not seeing the smarter way
7 commentaires
Walter Roberson
le 26 Oct 2012
I think that could probably have been done through dynamic structure field names.
Sean de Wolski
le 26 Oct 2012
I think I would want to know the bigger picture of how she got to that position in the first place.
@Walter - I can't see the link between dynamic field names and refreshing an anonymous function.
@Sean - I imagine the scenario was similar to coordinate descent. You want to optimize a function by alternatingly letting 1 parameter be free and the others fixed.
I agree that there are times when EVAL is the only way, but I could probably count them on one hand in 8 years of MATLABing.
I wonder if using INLINEs would have worked for Alicia? Like Sean said, one would have liked to see a simple example of what she was doing...
Sean de Wolski
le 26 Oct 2012
@Matt J, I would think a few simple isempty checks would handle that i.e. pass in the same things every time, some are just empty.
Have a great weekend!
Walter Roberson
le 26 Oct 2012
Instead of creating a string that lists the variable names, and then having to eval() the string to reach the variables, you can do something like
@(t) isp(t, MyStruct.(varname1), MyStruct.(varname2))
Matt J
le 26 Oct 2012
okay!!
If you migrate from Matlab to Simulink, you will find that the community and documentation uses globals fairly widely. It was a bit of a shock.
1 commentaire
Guy Rouleau
le 9 Nov 2012
K E, can you give a few examples? I use Simulink all day long, but almost never globals. I am curious to see which examples you are talking about.
Kurt Stewart
le 20 Mar 2019
0 votes
Globals that get redefined by other functions can be a problem. If you are loading a global into the stack of a current function and dont change its value then it should be fine. The issue with Global variables come when you access them at the same time with two functions. To do this properly you need mutexs. Global variables can be useful for reducing the amount of copies of data that you pass from function to function due to no pointers being available in Matlab
2 commentaires
due to no pointers being available in Matlab
Steven Lord
le 20 Mar 2019
Are you using global variables to reduce the "amount of copies of data that you pass from function to function" for purposes of saving memory? If so, the copy on write behavior of MATLAB may help with that.
If you're using global variables so that one function can modify a variable and have that change propagate to other functions without needing to return that variable, it may be appropriate to create a handle class for that purpose. Alternately, if you have "helper" functions that are small and are only used by the one "main" function, consider nesting the "helper" functions into the "main" function so that they can share the variables.
Are there times when global variables are useful or even necessary? Just like the chainsaw Jason and Sean discussed above, sure. But it probably shouldn't be the first thing you teach a novice how to use.
Catégories
En savoir plus sur Variables dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!