Make it simpler …

Why is JavaScript provoking people to write unnecessarily complicated code? Even people who usually come across as relaxed and not as feverish JavaScript zealots.

Albert said it all.
Albert said it all.

For example one Mr D.Edwards. After reading through his mainly good code , in all of my innocence, I stumbled upon some surprising obfuscations. For example he has this “awesome” javascript construct present, which allows the code to “know” if it is executing inside IE:

Ok, ok … not to panic. Let me explain what the code above does. First of all it evaluates a piece of JavaScript code inside a string. And a lot of people with any JavaScript experience, will rightly advise you not to use eval() if you can avoid it at all.

Next. This “magical” code in a string, gives the value false,to the variable isMSIE. Then this code uses Microsoft feature called “JScript conditional comments”1, which I have nothing against.This feature, allows for code that gets evaluated only if code is executed inside the IE. The whole “magic” above, is wrapped inside this :

 

A basic JScript feature to conditionally  wrap the code to be executed only if JScript2 is parsing this code. But.
Inside the string the code also (for some unknown reason) checks the value of the “conditional compilation constant” ‘@_win32’ which is ‘true’ if code executes on win32 platform. Also above we have this funny ‘@\x5fwin32’ “thing”. Which seems like an unnecessary hack? Maybe it is used to allow this string, to be properly evaluated by the eval() function ? I do not know.

What a lot of densely compressed magic, one might think ? Well … I beg to disagree.

Code needs to be maintainable. Higher the level of obfuscation is, the lower the level of maintainability is. I think this is a prime example of an obfuscated code which can be made much simpler and easy , or easier, to understand by others. This is my simple version :

This solution works and does what it is supposed to do. And it is almost hilariously simple. Make it true first , and second, if in IE switch it to false.

There is no reason to additionally check the value of @win32. As simple as that. This solution works, it is simple and it is easy to understand. And the simplicity is a quality which is very important. It leads to a robust code which is easy to maintain.

Maintenance of code always happens by “significant others”. Complicated and obfuscated code is very often removed, if someone has to maintain your brilliance long after you have left the project. Never forget that.

If you want your code to survive the test of time, keep it simple. Working right, and working well.

 


1: Not to be confused with conditional “compilation”. There is no “compilation” in javascript+browser context.

2: JScript is Microsoft version of javascript.

2 thoughts on “Make it simpler …”

Comments are closed.