Archive for February, 2006

Gentleman’s Privates

Saturday, February 25th, 2006

In Javascript, you can have true private methods and fields, but it comes at a cost…both a readability cost and a performance cost. It basically involves creating closures in the constructor. Those closures are attached to ‘this’ reference and since they are closures defined in the scope of the constructor, they have access to any of the constructor’s local variables. An example may prove useful:

function Foo(){
var privateField = “Only setPrivate and getPrivate can see this field”;
this.setPrivate = function(value){
privateField = value;
}
this.getPrivate = function(){
return privateField;
}
}

I first learned about this over at Douglas Crockford’s site (this guy knows his stuff…read it!). He as great explanation of private members in javascript.

At the moment (and I’m sure this can change) I feel this is a bit overboard for most cases. I think I may be more turned-off by the readability…I just can’t bring myself to be ok with having the methods defined IN the constructor. I understand this is the only way to have TRUE private members…but I’m thinking that I’d be ok with Gentleman’s Privates. That is to say, using a notation that tells the user (developer using, reusing, extending or otherwise interacting with the class or an instance of the class) that the variable is meant to be private…”so, be a gentleman and don’t access it directly”. Sure, this leaves the door open for abuse…breaking encapsulation. But if the convention is known…then the developer KNOWS they shouldn’t be directly accessing the variable (even though the language doesn’t enforce it). And by doing so, they run the risk of becoming too tied to that implemenation of the class.
Naming conventions for private members is done all over the place…even in languages that support true private members (no I don’t). I can’t find it with a quick google, but I’m sure I first heard this approach in reference to Perl. It was something to the effect of describing Perl as a “Gentlemen’s Language”. Basically meaning that the language didn’t enforce any access restrictions, but the developers were ‘gentlemen’ about it, and followed the rules of the naming conventions. The typical convention for private members (as I understand it) is to prefix the variable with an ‘_’ character. In my experience, many developers understand this convention.

I prefer the Gentlemens approach to private members in javascript.  I don’t want to get hung up on trying to lock my object/class down to prevent any abuse: jumping through hoops trying to get access priveleges that are not enforced by the language. Let’s just be gentlemen about it.

Ok, all that said, I was thinking a bit about the naming convention itself. The ‘_’ prefix is well known, so it’s tough to just say ‘lets change it’, but I’m thinking…’lets change it’. How about ‘ _’? That is SPACE-Underscore…as a prefix for private members. This forces the developer to access the member via the bracket notation: obj[’ _somePrivate’]. This has a few benefits in my mind. First, it isn’t natural which means you’ll have to think about it and say “well…it IS private…maybe I should try something else”. Second, its not pretty…so a developer may decide to modify the design (if its his code) so that the member is exposed, or it supports whatever the caller was trying to do via a new method.

The negatives are actually the same as the benefits…but the caller is the class code itself. So the class has to access its private members through the same bracket notation, which is still not natural, and still not pretty. Given that the private members should (by definition) only be accessed by the owning class, this may seem like just an annoyance and may find developers quickly abandoning it.

In the end…I guess I’m up in the air about it. I like that it will make it more work for developers to access it when they shouldn’t (from outside the owning class)…but I don’t like that it will also be more work for developers to access it when the can/should (from inside the owning class). And in the end, maybe ‘_’ should send up the same flag to the developer as “[’ _’]”.

What are some of your thoughts?

Laying tile

Saturday, February 25th, 2006

We managed to make some headway last night laying the ceramic tile.  My hands still have a bit of stubborn tile adhesive on them as I type.  The base-boards were pulled as soon as I got home from work.  I’d planned on going to a coffee shop and working on my presentation, but I figured I could do that Sat and Sun.

Once the baseboards were up, it was time to think about where to lay the first tile…and how the others would fall around it.  This took a long time.  Its tough trying to map out the tile layout to get as many full tiles as possible (and keep them straight!).  We finally decided to snap a chalk-line and I started tiling while Aislinn went out to get more stuff for showing the house (vases, borrowed rug, paintings…stuff we just don’t have, but make the house show better :)).

I managed 30 tiles before she got back.  I only had 4 that had to be modified.  2 just needed a corner chopped…and 2 needed a notch.  The notches sucked.  I didn’t want to drag out the wetsaw with the boys sleeping (it was 10 by now).  I managed to chop the corner off of both…and ‘liquid-naile’d them both back on.  It worked out well.

So now I’m here at the coffee shop working on my presentation.  (And blogging a little).

Class.js - third time is the charm

Friday, February 24th, 2006

Say you want to override a method by adding a new impl directly to the instance. callSuper should be callable from that new overriding method and it should result in the closest ancestor impl being called…even if it only has to go as far as the instance prototype (technically, the instance’s constructor’s prototype). Well…the code I had up wouldn’t really support that. It would skip over the instance prototype. The latest will support this.

Maybe I should start versioning :) I definitely need to have tests.

Class.js

Bug in Class.js

Thursday, February 23rd, 2006

Found a bug and fixed the version that the previous posts point to: Class.js

Basically, the callSuper would not work if the method was not implemented at the beginning of the chain. For example if you have classes A, B, and C, (where B extends A and C extends B) and B and C implemented a toString then calling toString on an instance of A would result in an infinite loop. With the updated code, an array is built to represent the prototype chain, and that array is traversed IN REVERSE until it finds the calling function. Then it grabs the NEXT prototype in the chain and executes the method if it exists. No need to search and keep digging throught the chain to see where it is implemented…because the built in chain traversal will do that for us (pretty much the same reason the bug was occurring).

Anyway code is fixed and re-posted.

Finally Posted Code…and I’m moving

Thursday, February 23rd, 2006

I got the Javascript Inheritance code uploaded: Class.js

I’ve been keeping pretty busy getting our house ready to sell. About 2 weeks ago we found a house in U. City that we love…put an offer on it and it was accepted. Pending all inspections and such, we close March 30. So…we now have to move up our plans to sell our own house and do a few years of upgrades and painting in a week or so. So far Aislinn has been really busting her butt painting EVERYTHING and I’ve been remodeling the master bathroom and fixing random other things (and breaking others :)). I’ve gotten pretty comfortable with plumbing too. Then there is the presentation on OOJS on Monday. It’ll be fun, but so far, finding time to prepare has been almost impossible.

SO, about the code (if you haven’t been following the posts on it). The Class.js file provides an implementation of Classical Inheritance for Javascript. It does not involve newing up an instance of the superclass to set as the subclass’ prototype…I really didn’t like that approach. The implementation still builds a nice prototype chain though. It basically create’s an inline function…then sets that function’s prototype to the superclass prototype. Then it news up an instance of that inline ‘class’ and sets the subclasses prototype to that instance. So the prototype chain for instances of the subclass still actually contain a reference to the superclass’ prototype.

The code also adds a callSuper method to the subclass’ prototype. callSuper can be called from anywhere in the subclass and will result in a call to the superclass’ implementation of whatever method the call resides in (actually…it will find the first implementation further ‘up’ the ancestor chain…not neccessarily in the superclass). So, effectively, it knows how to find the overridden version of the calling method…and calls it. For Example:

function Shape(){
}
Shape.function.toString = function(){
return "Shape";
}
function Square(){
}
Class.extend(Square, Shape);
Square.prototype.toString = function(){
var str = this.callSuper();
return str + ': Square';
}

Screen Reader Form Navigation Events

Thursday, February 9th, 2006

The guys at Access Matters have put together a sweet chart that shows what form navigation events are fired when using screen readers . Man I wish I’d had this at the USPS.

A Stab At Javascript Inheritance

Wednesday, February 8th, 2006

Here is the working code for implementing an inheritance model in javascript. Most of the code is actually for handling the callSuper functionality (calling an overridden method in the super class). The actual subclassing code could be reduced to 4 lines if that bit were removed. Just highlights the “are we sure we need this” question. But its DAMN cool…and I had fun, so it was worth the time.

This script requires arguments.callee.caller to work…that is the magic the code uses to figure out where in the prototype chain to begin the search for the super class’ implementation of the method currently being called. There were some minor tweaks I had to do to get it to work in IE, but it works. As a bonus, calling the ‘callSuper’ method from a constructor will work too.

I’ll probably wind up putting this in a library sometime…I just wanted to get it here and get some eyes on it. Enjoy
Update: I removed the code because it looks horrible on here…I’ll upload and provide a link when I have proper access.

Example Code…this is sickeningly basic…but its what I used while I was putting this together. I’m not sure why I didn’t fire up jsunit to do this thing right (tdd). Oh well…I blame the insomnia.


function Shape(){
this.shapeCalled = true;
}
Shape.prototype.toString = function(arg){
return 'Shape '+arg;
}

function Rectangle(){
this.callSuper();
this.rectangleCalled = true;
}
Class.extend(Rectangle, Shape);
Rectangle.prototype.toString = function(){
var mssg = this.callSuper(’test from rectangle’);
return mssg + ‘ : Rectangle’;
}

function Square(){
this.callSuper();
this.squareCalled = true;
}
Class.extend(Square, Rectangle);
Square.prototype.toString = function(){
var str = this.callSuper();
return str + “:Square”;
}

Update: Finally posted the code here: Class.js. Getting a house ready to sell will keep you busy :)

Javascript Inheritance and callSuper

Wednesday, February 8th, 2006

So far I’ve got only 2 problems with the inheritance mechanism from the earlier post.
- it doesn’t allow for multiple inheritance. I’m ok with that…coming from java it is just what I’m used to. However, it doesn’t rule out the possiblility of employing a Class Augmentation approach from being used along with it.
- navigating the prototype chain is tricky. Since the code is ‘resetting’ the constructor property on the prototype…I don’t see a way for program code to traverse the chain (aside from using the non-standard ‘__proto__’ property). This is fine for the code that is aware this is the case…it can look for the ’superClass’ property that the inheritance code is adding…but yeah, thats a ‘gotcha’ for when you are wanting to integrate with another library that wants to (for whatever reason) traverse the chain.

I couldn’t sleep tonight, so I dabbled with adding support for calling overridden superclass methods. It was really more as a fun exercise than anything else as I still don’t see a huge problem with just directly calling the superclass method like so: SuperClass.prototype.someMethod.call(this, arg1, arg2);

So the result is the ability to, from any method (i.e. not the constructor) call this.callSuper(); and it will call the superclasses implementation of the method that you are in! You can also call this.callSuperByName(’methodName’); and it will call the superclasses implementation of the method with the given name. It is intelligent enough to begin searching the prototype chain from the depth that the code that called the ‘callSuper’ method is located.

I’ll post the code soon…need to get ready for work (and I want to make sure it works in more than just one browser :)).

Prototype Chain

Sunday, February 5th, 2006

I’m doing a presentation on OO Javascript to Daugherty developers on the 27th. In preparation I was doing some digging online (mostly to make sure I really DO know what I’m talking about) when I ran into an article that talked about the prototype chain. While I was aware of this…I don’t know if it was ever spelled out for me…it was just…there. So it got me thinking about a different way to handle subclassing.

There are 2 primary forms of subclassing I’ve seen:
- Copy the methods from the SuperClass.prototype to the SubClass.prototype
- Set the SubClass.prototype to a new instance of the SuperClass.

I use the first and it actually works pretty well. The only problems I have with it are that it (probably?) won’t work with the instanceof operator (actually…I’ve never used it. I just learned about it, but I’m guessing it doesnt’ work), and that it gets hairy when you do multiple levels of inheritance and are trying to keep track of the heirarchy (so you can do stuff like super.someMethod();). But honestly…both of those are probably smells anyway. Don’t subclasses always know who theier superclass is anyway? The SubClass code could just say: SuperClass.prototype.blah.call(this, argv);…not ‘pretty’, but it works. The point is, that the subclassing via copying methods from the parent prototype works, but it still has its problems.

The second I’ve never liked. What if the SuperClass constructor needs arguments? What if it does something expensive, or needs the DOM, or any number of problems. The ’solutions’ I’ve seen to this are to add code to the SuperClass constructor to determine if it was called with no args. If it was, then do nothing. But really, this is only feasible for a constructor that takes args…what if it was a no-args, but did something expensive…or assumed some state of the browser that is not true at the time of the ‘extend’ call?

For whatever reason, the article about the prototype chain triggered something and got me thinking about a different approach. My first attempt was to just set the Subclass.prototype.prototype to the SuperClass.prototype. That didn’t work. I needed to know more, so I dug into the ECMA 262 spec…not sure why that hadn’t happened before. The spec talks about an IMPLICIT (i.e. not accessible) ‘[[prototype]]’ reference. In essence, every instance ALWAYS knows what prototype it was created based on. The prototype chain heavily relys on this implicit reference to resolve properties. This means that the prototype instance on the SubClass should really have a reference to the SuperClass.prototype for it to truly take advantage of the OO features that ECMA script is defining.

So, at face value that means setting SubClass.prototype to a new instance of the SuperClass. I still don’t like that. However, this is Javascript…where everything can be dynamic. So a new idea was forming. Why not create a new, in-line subclass of the SuperClass and set the SubClass.prototype to an instance of THAT in-line subclass instead? Here is the idea:


Class.extend = function(SubClass, SuperClass){
var innerSuperClass = function(){};
innerSuperClass.prototype = SuperClass.prototype;
SubClass.prototype = new innerSuperClass();
SubClass.prototype.constructor = SubClass;
}

This approach seems to be the best of both worlds…it builds a nice prototype chain, and does not require the SuperClass to be overly careful about calls to its constructor.

Is there something I’m missing here? Is there something about this approach that is just..bad, that I may have missed. Please let me know. I’m sure I’m not the first to do this. Until hearing otherwise, this is the approach I will be using.