Thursday, December 4, 2008

Where did that come from?

Have you ever tested code and some inexplicable error keeps happening over and over even though you can swear that you removed or corrected the offending code. I can't count the times this has happened to me. I just worked my way through this very problem.

I was working on some javascript and I kept getting an error about a function/class not being a constructor. I kept changing code and adding alerts but I could not figure out why FF or IE couldn't identify my function. I went so far as to delete everything from the function and leave a lone alert. Still no luck. After hours of hair pulling, which is hard since I have very little hair, I finally discovered the problem. Two scripts on the page had the same name. Problem was that while I was importing my script the other script was magically being pulled in via an ajax/eval. So the import of the script went something like this HTML -> import script 1 -> script 1 has a dependancy on script 2 -> script 1 import script 2 -> script 2 has a dependancy on script 3 -> script 2 import script 3. Sounds simple enough right, well it would be if the HTML page either imported all of the necesssary scripts or even if you had a nifty dojo like require function so that scripts could explicitly import their dependancies. Oh no, what I had to deal with is some monkey writing a utility function that pulls in all of the scripts I could ever possibly need for every possible HTML page. That means that every script written for any portion of the site gets pulled in; lets see that's 76 scripts with 4 duplicates, 74 I don't even use or need and 3 of those are libraries like DWR and ProtoType, great libraries but I don't need them imported for every single page on the site.

Lesson: Fight the erge to bring the entire arsenal of weaponry to every fight. In other words stop trying to predict what will be needed for the future, let the very smart and talented developers who come after you decide what tool they need to solve their problems. Your code will be smaller, easier to read and best of all easier to modify. Poeple suck at predicting the future and the sooner developers understand this and write their code for what is and not for what might be the sooner you will stop writing impossibly complex and useless code.

No comments: