473,386 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

A valid use of eval?

After reading much on the evils of eval, I have a question using my
own personal use of the function...

We have a reports system that will generate reports based on a number
of parameters available on a blotter at the top of our report system.
Each report could (and does) use a combination of some (but not all)
of these 15 parameters.

Each report also has a series of precalculations that need to be run
before the report can execute.

My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call

"ReportName('parameter','parameter','parameter ');"
which is the Evalled to execute

As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.

My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use? I realize that my example doesn't
necessarily flesh out enough detail regarding judgement of the entire
report launching concept, but trust me when I say that "eval" has cut
my code down by several 100 lines!

Regards
Mike
Jul 23 '05 #1
9 1840
Mike wrote:

Hi Mike
After reading much on the evils of eval, I have a question using my
own personal use of the function...

We have a reports system that will generate reports based on a number
of parameters available on a blotter at the top of our report system.
Each report could (and does) use a combination of some (but not all)
of these 15 parameters.

Each report also has a series of precalculations that need to be run
before the report can execute.

My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call

"ReportName('parameter','parameter','parameter ');"
which is the Evalled to execute

As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.

My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use? I realize that my example doesn't
necessarily flesh out enough detail regarding judgement of the entire
report launching concept, but trust me when I say that "eval" has cut
my code down by several 100 lines!
I think you just described a perfectly good situation to use eval.
:-)

And people who think eval is evil are zealots IMHO.
If it suits your needs: use it.

It is just that many people use eval where they could also use a perfectly
normal, valid, easy-to-read alternative...

Regards,
Erwin Moller

Regards
Mike


Jul 23 '05 #2
Lee
Mike said:

After reading much on the evils of eval, I have a question using my
own personal use of the function...

We have a reports system that will generate reports based on a number
of parameters available on a blotter at the top of our report system.
Each report could (and does) use a combination of some (but not all)
of these 15 parameters.

Each report also has a series of precalculations that need to be run
before the report can execute.

My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call


If you're building this string dynamically on the server, why not
just build the function call dynamically, instead?

Jul 23 '05 #3
You are parsing a string to construct a function call,
then using eval on that.
The following sample script shows how to avoid your use of eval:

<script type='text/javascript'>
function ReportName () { // just shows the arguments
report = "";
for (var i=0;i<arguments.length;++i)
report += (i ? ", " : "") + arguments[i];
alert (report);
}
var ReportString = "ReportName~my param~parameter 2~parm 3";
var aRep = ReportString.split("~");
window[aRep[0]].apply(window, aRep.slice(1)); // replaces the eval
</script>

Something that struck me in your description: that string you are
constructing - would it not make sense to have it be an array in
the first place? Or better yet, an object where each key is the
parameter name. Strikes me that your code might be more
understandable that way.

For example,
oReport = {}; // this object collects report parameters
oReport.functionName = "ReportToRun";
oReport.source = "Mike's database"; // parameter 1

Csaba Gabor from Vienna
Mike wrote:
After reading much on the evils of eval, I have a question using my
own personal use of the function...

My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call

"ReportName('parameter','parameter','parameter ');"
which is the Evalled to execute

As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.

My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use? I realize that my example doesn't
necessarily flesh out enough detail regarding judgement of the entire
report launching concept, but trust me when I say that "eval" has cut
my code down by several 100 lines!

Regards
Mike

Jul 23 '05 #4
mi**********@uk.standardchartered.com (Mike) writes:
My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call

"ReportName('parameter','parameter','parameter ');"
which is the Evalled to execute
This fails if any of the parameters contain the single-quote
character.

One of the reasons using eval is dangerous is that turning values into
literals is neeed, and forgetting it will work in most cases ... (yes,
that is bad, not good!)

I assume the "ReportName" function is defined as a global variable.
Then try this as a global function:
---
function doReport(codedString) {
var parts = codedString.split("~");
this[parts[0]].apply(this, parts.slice(1));
}
---
No eval, and probably shorter than your code :)
As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.
Probably not too dangerous either.
My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use?
It depends. If you are targeting browsers too old to have "apply",
it's probably the simplest way. You could do:
---
function doReportNoApply(codedString) {
var p = codedString.split("~");
this[p[0]](p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],
p[10],p[11],p[12],p[13],p[14],p[15]);
}
---
since you know that there are at most 15 arguments.
I realize that my example doesn't necessarily flesh out enough
detail regarding judgement of the entire report launching concept,
but trust me when I say that "eval" has cut my code down by several
100 lines!


Sounds likke 100 lines deserving to be cut :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5
JRS: In article <7b**************************@posting.google.com >,
dated Thu, 14 Apr 2005 07:45:07, seen in news:comp.lang.javascript, Mike
<mi**********@uk.standardchartered.com> posted :
After reading much on the evils of eval, I have a question using my
own personal use of the function...

We have a reports system that will generate reports based on a number
of parameters available on a blotter at the top of our report system.
Each report could (and does) use a combination of some (but not all)
of these 15 parameters.
But each report function can be given, with negligible overhead, all 15
parameters - you're only passing the identity of an object, and within
the report function you can give sensible names to the wanted ones and
names such as x0 x1 ... to the others. Calling them all x would be
inelegant, unless it can be shown both legitimate and safe.

You can now put the report function names in an array

function RepFn0(p1, ..., p15) { ... }
function RepFn1(p1, ..., p15) { ... }
function RepFn2(p1, ..., p15) { ... }
....

var AllRepFns = [RepFn0, ...]
Each report also has a series of precalculations that need to be run
before the report can execute.
The entries in AllRepFns can be enhanced to be objects containing not
only the function name but also a list of names of precalculations.

....
My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call

"ReportName('parameter','parameter','parameter'); "
which is the Evalled to execute
.... and execute by AllRepFns[n](P1, ..., P15)

Or the array could be generalised into a simple Object, using the name
of the report to select the correct RepFn# or the Object holding it.

You end up with table-driven control, with the table held in objects
and/or arrays.

Take a glance at "Data", in the textarea, at the end of <URL:http://www.
merlyn.demon.co.uk/holidays.htm>, and similar in the source.
As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.
All you need do is see if the process is significantly slower using eval
for (say) the quickest and slowest functions in comparison with a direct
call, on your slowest target machine. Not detectably but significantly.
My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use? I realize that my example doesn't
necessarily flesh out enough detail regarding judgement of the entire
report launching concept, but trust me when I say that "eval" has cut
my code down by several 100 lines!


It is at worst a rare misuse, IMHO.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
fox


Mike wrote:
After reading much on the evils of eval, I have a question using my
own personal use of the function...

We have a reports system that will generate reports based on a number
of parameters available on a blotter at the top of our report system.
Each report could (and does) use a combination of some (but not all)
of these 15 parameters.

Each report also has a series of precalculations that need to be run
before the report can execute.

My solution was to create a string for each report
"ReportName~parameter~parameter~parameter"
built dynamically, and eventually parse the string in an execution
function that resolves it to a full function call
window["ReportName~parameter~parameter~parameter"](/*optional args*/);

should have the same result... no eval() necessary...

"ReportName('parameter','parameter','parameter ');"
which is the Evalled to execute

As this is only a single line of code to Eval, it seemed the most
logical and probably reasonably inexpensive.

My question is is this a common misuse of eval, or one of the few
cases where it makes sense to use? I realize that my example doesn't
necessarily flesh out enough detail regarding judgement of the entire
report launching concept, but trust me when I say that "eval" has cut
my code down by several 100 lines!

Regards
Mike

Jul 23 '05 #7
Interesting idea, the apply code. I'm going to look into this,
possibly in combination with Csaba's ideas on using a Report Object.

Perhaps a good combination is to build a report object with an array
for parameters, and then use apply function to apply said array to the
report function?

I guess it makes it nice and readable too, and I have the added plus
that I can use array methods to tag additional items to the parameter
array if required (sometimes the report is able to recall itself with
additional optional parameters to allow drill down), which would be
easier to understand than a bunch of gratuitous splits and dynamic
function building.

Since I'll be calling the launcher function seperately, I can just pull
the reportname from the Report object and apply precalculations if
necessary before launching.

Should I then have an array of those objects?

Sigh... it all gets complicated way too quickly. One of my favourite
and worst things about Javascript, is that it really makes it easy to
"go" with a idea and get really far before discovering a Better Way :-)

I think I'm going to have to go back to coding in Paper Script for a
bit...

I think I quite like this approach...

Jul 23 '05 #8
Maybe a generic scenario will help get this solved.

Let's say for example I have 3 reports with the following parameters
OrderReport (Location [,Customer Number]);
ProductReport (ProductId [,Location [,Customer Number] ] );
StockReport (ProductId [,Location [,ProductAisle]]);

Initially from a combo, you could run an Order or Stock report for a
location, a Product Report for a specific Product.

Once the report is up, it could contain within it a dropdown of all
Customers (Order), Locations (Product/Stock Report), that would rerun
the report with that added layer of detail. (As the report is actually
dynamically generated XSLT in my case, lets just assume that it is
necessary to rerun the report when drilling down)

Let's say that there are 2 dropdowns at the top of the form for these
parameters (Location, ProductId) which always have at least one value.

Should I build an array of those functions? How do I ensure that those
functions get the right parameters each time, but can also be called
from within the reports with additional parameters?

Should the parameters be summarily scrapped in this instance and
replaced with a "parameters object" that contains all of the possible
parameters that each function can dip into as and when required?

Thanks so far to all who have contributed to this thread. Really great
ideas being thrown around.
Mike

Jul 23 '05 #9
Maybe a generic scenario will help get this solved.

Let's say for example I have 3 reports with the following parameters
OrderReport (Location [,Customer Number]);
ProductReport (ProductId [,Location [,Customer Number] ] );
StockReport (ProductId [,Location [,ProductAisle]]);

Initially from a combo, you could run an Order or Stock report for a
location, a Product Report for a specific Product.

Once the report is up, it could contain within it a dropdown of all
Customers (Order), Locations (Product/Stock Report), that would rerun
the report with that added layer of detail. (As the report is actually
dynamically generated XSLT in my case, lets just assume that it is
necessary to rerun the report when drilling down)

Let's say that there are 2 dropdowns at the top of the form for these
parameters (Location, ProductId) which always have at least one value.

Should I build an array of those functions? How do I ensure that those
functions get the right parameters each time, but can also be called
from within the reports with additional parameters?

Should the parameters be summarily scrapped in this instance and
replaced with a "parameters object" that contains all of the possible
parameters that each function can dip into as and when required?

Thanks so far to all who have contributed to this thread. Really great
ideas being thrown around.
Mike

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: lawrence | last post by:
I have a string which I want to send to eval(). How can I test it ahead of time to make sure it is valid code? I don't want to send it to eval and get parse errors. I want to do something like...
3
by: PK9 | last post by:
I am looking for assistance in pinpointing the cause of the following exception. I am getting a "Specified Cast is not valid" exception on my page. I am trying to populate a datagrid. One of my...
3
by: Patrick Olurotimi Ige | last post by:
I moved some projects to another server and using the code below i get the error:- "String was not recognized as a valid DateTime" <asp:Label runat="server" width="40%" text=' <%#...
6
by: Alan Silver | last post by:
Hello, I am data binding a repeater that has a checkbox in the ItemTemplate. The data value coming out of the database is a char(1) field containing either "y" or "n". I want to use this value...
1
by: Grzegorz | last post by:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250">...
3
by: keithb | last post by:
Using a GridView, I get a "Specified cast is not valid" error when binding the Visible propery of a hyperlink control to a DataTable text field. The error goes away if I replace the data binding...
4
by: =?Utf-8?B?RXJpY2E=?= | last post by:
I am trying to dynamically create a javascript link. But, I get the following error: BC32017: Comma, ')', or a valid expression continuation expected. Here is the line I try creating the...
3
kovik
by: kovik | last post by:
I'd like to pass arguments from one function to another, but I can't seem to get it through my head to make it work. I wrote a function similar to PHP's array_map(), which runs all members of an...
2
by: Cirene | last post by:
I'm setting a databound label's backcolor and forecolor like this... <asp:Label ID="lblSampleColorScheme" runat="server" BackColor='<%#...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.