Do you remember the first time you did things which made your guardian angel sob? But you did it again, didn’t you? How does it feel? But when you get used to doing it over and over again, you never notice it at all right? Right.
I was told that eval is evil. But honestly, I was never told… I just have read it somewhere. Sigh, my conscience pulls me away from lying (again). Well, anyways, enough for the old-school Safeguard commercial, here goes my head’s brainstorm — or brainhurricane — for its being fast and direct-to-the-point-ish thingy.
I was working on a very small project with a very less time to work on it. By less time I mean less than four hours. Basically the project was some sort of a calculator, which has not-so-dynamic formulas which are inputted by the user. I was not able to find a good formula parser (provided that I did not have an adequate internet connection and the time constraint was forcing my hands to tap the keys), so I wrote my own. Here goes my code:
public double parseFormula(double value, String formula){ String expression = formula.replaceAll("value", value + ""); ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); try { return Double.parseDouble(engine.eval(expression).toString()); } catch(ScriptException exception) { exception.printStackTrace(); } return 0; }
They said eval() is evil especially if it’s in javascript, but the code is in Java, so I don’t need to worry. Or is it?..
I used a javascript engine for a Java program! Wait, what?! Oh, no, the evil thing is lurking… But I shouldn’t care anymore since it was just a very small project. The good thing is that it works! I did not think that the program will be modified in the future thus eval() was a necessary evil.
The statement above made me think – why are Evil Geniuses called Evil Geniuses? Is it possible they used eval()?
*insert part where Perry raids Heinz because of doing eval()*