Path: news.mathworks.com!not-for-mail
From: "Steven Lord" <slord@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Why does everyone hate 'eval'?
Date: Thu, 11 Dec 2008 14:12:19 -0500
Organization: The MathWorks, Inc.
Lines: 60
Message-ID: <ghromj$f8g$1@fred.mathworks.com>
References: <ghrlim$oqo$1@fred.mathworks.com>
Reply-To: "Steven Lord" <slord@mathworks.com>
NNTP-Posting-Host: lords.dhcp.mathworks.com
X-Trace: fred.mathworks.com 1229022739 15632 144.212.105.187 (11 Dec 2008 19:12:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 11 Dec 2008 19:12:19 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
X-RFC2646: Format=Flowed; Original
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
Xref: news.mathworks.com comp.soft-sys.matlab:506405



"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message 
news:ghrlim$oqo$1@fred.mathworks.com...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO,  DO NOT 
> USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but 
> totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval 
> as highly motivated.
>
> Comments?

Others have posted their own reasons, but one additional reason is that it 
can be dangerous.  If one of the cases where you think eval would be "highly 
motivated" is something like:


function y = evaluateAtXequals5(equationString)
x = 5;
y = eval(equationString);


to evaluate a user-entered expression at x = 5 ... you're giving your user a 
loaded weapon and trusting that they will only fire it at the target you've 
set up.  That trust may be betrayed, either through malice or by accident. 
I'm sure you can come up with a 'payload' for this function that could cause 
some havoc and/or destruction (remember SYSTEM works inside an EVAL, BTW.)

Now the reason I suggest that users not do something like:

for k = 1:10
    eval(sprintf('a%d = 1;', k));
end

is that it's IMO much harder to read than:

for k = 1:10
    a(k) = 1;
end

or:

a = ones(1, 10);

With the last two, it's obvious upon looking at the code that we're working 
with a variable a, and it doesn't take much longer to work out that a will 
be a 10-element vector at the end of the code.  With the first code, it'll 
take longer to figure out that it's creating 10 variables, a1 through a10.

-- 
Steve Lord
slord@mathworks.com