Wednesday, September 22, 2010

With Considered Harmful (But Not OUR With)

I've been promising this post for a week already, but having trouble getting around to it.  So here's a short, sweet version.

Douglas Crockford has a fabulous discussion of how JavaScript's designers messed up on JS's with statement.   JS's with is much like our with, except naturally (but not sufficiently carefully!) extended to an OOP context. 

Roughly speaking, with object-expr { stmt; ... } places the fields of the object returned by evaluation of object-expr into the static scope of the contained statements. 

Now, if we refer to (as Crockford says) the identifier bing inside the with, which bing do we get?  If the object has a bing field, we'll get that one.  If it doesn't, we'll get one from a broader scope.  How do we tell which it is?

In Java, answering this would be annoying but could at least be statically determinable.  You could limit the fields to those that are (currently visible, given privacy restrictions) members of the static type of object-expr

It's far worse in JavaScript, where an object can gain fields dynamically during execution; so, without looking at the entire program execution (not even just the dynamic context of the statement), you cannot know what will be accessed.

So, read Crockford's post, but don't stop there!  Crockford's remedial JavaScript article is also a brief but fascinating exploration of language design issues and the standardization process.

Cheers,

Steve

P.S. I consider automatic prepending of this. to members inside Java methods to be a poor design choice similar in nature to the with design.  (Have you ever screwed up code because of that "helpful" syntactic sugar?  I have!)

No comments:

Post a Comment