Today is a good day to code

JavaScript and Object Oriented Programming

Posted: December 31st, 1969 | Author: | Filed under: java, Programming, Uncategorized | Tags: | No Comments »

JavaScript and Object Oriented Programming

Picture of IrvinFor some time now I have advocated using what I, for lack of a better term, call object oriented style coding when approaching JavaScript. Recently, Joseph Smarr talks about some of the challenges faced by developers who try to do too much with JavaScript. He brings up some good points, I'd like to discuss some of his findings, and add a few that were left out.

He talks about every line having a cost with JavaScript and being brief when writing it. I would go along with that, with the caveat that if you are writing something with JavaScript's condensed notation and no one including yourself will be able to understand it in a year, you should probably go ahead and write it out longhand with comments, whether you leave the comments in when you release it is up to you, but I think the extra cost in performance is worth clarity.

You have to be willing to not make an object out of everything. In lots of ways, we have to “kill our darlings” to borrow a literary term, in that you have to be willing to break encapsulation, destroy design patterns, and do some hacking for performance. It is important to remember that with languages people typically use OO for, the compiler will take out redundant statements, and optimize away some of the things you have done to maintain sane code. With scripting languages, especially JavaScript, we don't have that luxury. That elegant factory pattern that looks so good in the code may, and probably will fall apart as far as execution performance. Unfortunately, many developers will not compromise the ideals they have been taught once they reach this point. So we end up with slow performing UIs that could be fast.

One thing that Joseph Smarr doesn't talk about is taking a hard look at what really needs to be done on the client. It is critical, when profiling to determine if the speed of a round-trip to the server is worse than the performance of your code against the client. It is important to think about ways in which the beefy server can do some processing. As sexy as a fully SOA is, if it performs like a dog, no one is going to care what the technology is behind it.

Many of the best developers refuse to work with JavaScript because of these things, and it is a shame because I think these are the people who are best in a position to change some of the negative aspects of the language. Also, writing procedural code forces some efficiency while OO seems to allow just about anything. If you can't handle the prospect of writing JavaScript, try C, not C++ it is the same sort of thing.