systematic: Do not use global, don't use eval
36 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2012-10-26
编辑:Jan
2012-10-26
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
2012-12-30
@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.
采纳的回答
Matt Fig
2012-10-26
EVAL is evil: Experience! Not just my own experience. Many times on CSSM and even here on answers a user asks, "How can I create these hundreds variables A_1, A_2,..." We try to tell him not to do it. Then a few days later he comes back, "I can't figure out how to process my hundreds of variables!" or "Why is my code so slow?" or "I can't find the bug in my code." And guess what? Nobody can help because the code is a mess of strings that is nearly unreadable. When it is not necessary, why use it? Why teach a beginner to program is such a way?
I do agree that there are times when EVAL is the only choice - fine. Just because there are exceptions doesn't mean that it should be the rule to use it. I would rather a user learn to program with efficient variable storage techniques, and program using best practice standards, and only much later discover EVAL.
Globals not good: Experience! In my work I help others with MATLAB. Beginners dive right in to globals because they think using them is easy. They are also easy to do wrong. Too often in my work I have to trace through all a user's M-files that use globals, and the base workspace, to find where the user accidentally made a change that is bugging up a entire complicated project. Each function has its own workspace for a reason(s) - and easy bug tracking is one. I always end up teaching people to program by careful data management rather than relying on globals. Usually they have less problems after that with "Where the @#$#*@ is the bug!"
They are another one I would rather see someone discover much later in their programming career. By that time they should know all the pitfalls and how to manage things carefully anyway.
I liken these things to using GOTO. Sure, one can use it just fine, and some may even prefer it to structured programming. But that doesn't mean it is a good idea - especially for beginners. Just like no Intro To MATLAB book I have seen teaches the user to turn to EVAL and globals (in fact many discourage these things), we as more experienced users ought to teach best practices and use these things only as necessary when coaching novices.
0 个评论
更多回答(8 个)
Jason Ross
2012-10-26
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 个评论
Jason Ross
2012-10-26
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
2012-10-26
On that note, I need to put a new chain on the saw before Sandy comes through...
Sean de Wolski
2012-10-26
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 个评论
Matt Fig
2012-10-26
编辑:Matt Fig
2012-10-26
+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! ;-)
Jan
2012-10-26
编辑:Jan
2015-1-9
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 个评论
Jan
2012-10-26
编辑:Jan
2015-1-9
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.
José-Luis
2012-10-26
编辑:José-Luis
2012-10-26
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 个评论
Jan
2012-10-26
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
2012-10-26
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 个评论
Daniel Shub
2012-10-26
I was trying to say I think appdata variables are global variable, but as Sean notes, a little better.
Matt J
2012-10-26
编辑:Matt J
2012-10-26
Here's a fairly simple scenario where EVAL seemed inevitable, though perhaps I'm not seeing the smarter way
7 个评论
Walter Roberson
2012-10-26
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))
K E
2012-11-8
编辑:K E
2012-11-8
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 个评论
Guy Rouleau
2012-11-9
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
2019-3-20
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 个评论
Steven Lord
2019-3-20
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.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!