“Hammer is evil” and the problem with mantras
About 90% of devs simply had little to no hands on knowledge of this maligned little function, because, of course, it is evil, no? Why would they have put any effort in getting to know about such a function. Most candidates were unable to tell us when it should, or must be used and many didn’t know what considerations must be taken into account when using it. Why would they know these things, we’ve all heard the mantra “Eval is Evil!”, so stay away and don’t ask questions.
And so we come to the problem with mantras. Google defines a mantra as “a statement or slogan repeated frequently”. Repetition is hardly conducive the thought, and when you actually think about it, eval is a tool, just like any other. When used correctly, it is good, when used incorrectly, it is bad. But never evil.
You wouldn’t call a hammer evil. When used with a nail and a piece of wood, a hammer is a perfect tool. When used to butter your bread, not so much. If people went around saying “Hammer is Evil”, wrote blog posts about it and smirked at you if they saw you using one, you’d tell them where to go.
So what are the correct uses of eval and what should be considered when using it? Many interviewees were surprised to know that many templating engines use eval to create the compiled functions. This is why it is suggested to compile your templates during the bootstrapping phase of your application. Eval is potentially slower to execute as the browser is not able to optimise it as much as normal code.
One of the biggest criticisms is that of security, but this is only an issue if you are evaling user input. Most of the uses of eval that I have come across having nothing to do with user input. Sometimes it is the only way to get something done.
Sure, you can swap out that line of eval for an anonymous function, but you’ll be in for a world of pain when it comes to debugging.
In closing I’d like to emphasise that all I am really against is dogma and mantras. If you want to talk best practises, I’m all ears, I just see little room for zealotry in the world of development. Disagreements can be settled by logic, demonstration and experience, ideas shouldn’t be shot down simply because “everyone says it is a bad idea”.
If you’d like to read more about the Milo Framework, you can check out Rolling Your Own Framework, and article we wrote on TutsPlus.