Maintainability of “eval”

I agree with all the points made in the article: security is not a concern if you take proper precautions & performance can be improved by using code generation.

However, the biggest downside of code generation is code maintainability. It is a lot harder to scan the code for potential errors.

Consider the validation example that you have provided.

The plain JavaScript version:

function validate(schema, data) {
for (var prop in schema) {
var value = data[prop];
if (typeof value != 'string') return false;
var pattern = formats[schema[prop]];
if (!pattern.test(value)) return false;
return true;

The code generation version:

var code = '';
for (var prop in schema) {
var data = 'data.' + prop;
code += 'if (typeof ' + data + ' != "string") return false;';
code += 'if (!formats.' + schema[prop] + '.test('
+ data + ')) return false;';
code += 'return true;';
var validate = eval('(function(data) { ' + code + ' })');

It easy to tell what is the intention of the first code fragment. It is impossible to tell what is the intention of the latter code without mentally compiling the to-be code.

Code obscurity is the primary cause of security vulnerabilities. This is the reason you often hear dynamic code generation as a culprit of security vulnerabilities. Inherently, eval is neither slow or non-secure. In fact, if you look into Node.js source code, you will learn that require is using vm to run all the code.

Written by

Software architect, startup adviser. Editor of Founder of

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store