Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

systematic: Do not use global, don't use eval

Asked by Azzi Abdelmalek on 26 Oct 2012

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 Comments

Jan Simon on 26 Oct 2012

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 Simon on 30 Dec 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.

Azzi Abdelmalek

Tags

Products

8 Answers

Answer by Matt Fig on 26 Oct 2012
Accepted answer

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 Comments

Matt Fig
Answer by Jason Ross on 26 Oct 2012

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 Comments

Sean de Wolski on 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 on 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 on 26 Oct 2012

On that note, I need to put a new chain on the saw before Sandy comes through...

Jason Ross
Answer by José-Luis on 26 Oct 2012
Edited by José-Luis on 26 Oct 2012

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.

It is expressed more eloquently here (not Matlab specific, but gives an idea).

1 Comment

Jan Simon on 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.

José-Luis
Answer by Daniel on 26 Oct 2012

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 Comments

Sean de Wolski on 26 Oct 2012

Two reasons guidata/appdata are better:

  1. 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.
  2. When the object is destroyed, all of the information is also destroyed and thus not lingering to cause headaches later.
Daniel on 26 Oct 2012

I was trying to say I think appdata variables are global variable, but as Sean notes, a little better.

Jan Simon on 26 Oct 2012

ApplicationData are global's in practice, when they are stored in the root object.

Daniel
Answer by Sean de Wolski on 26 Oct 2012

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 Comment

Matt Fig on 26 Oct 2012

+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! ;-)

Sean de Wolski
Answer by Jan Simon on 26 Oct 2012

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 command causes 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 command. Perhaps such problems appear suddenly, when you try to join your proghrams with the work of others to a greater framework. 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 Comments

Sean de Wolski on 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 ;)

Jan Simon on 26 Oct 2012

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 arose, 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 on 26 Oct 2012

Or as a function that you call that returns a value. Like pi().

Jan Simon
Answer by Matt J on 26 Oct 2012
Edited by Matt J on 26 Oct 2012

Here's a fairly simple scenario where EVAL seemed inevitable, though perhaps I'm not seeing the smarter way

http://www.mathworks.com/matlabcentral/newsreader/view_thread/321413#881676

7 Comments

Sean de Wolski on 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 on 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 on 26 Oct 2012

okay!!

Matt J
Answer by K E on 8 Nov 2012
Edited by K E on 8 Nov 2012

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 Comment

Guy Rouleau on 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.

K E

Contact us