Archive for the ‘Ideas’ Category

Selenium Remote Control

Tuesday, August 1st, 2006

So, as you might have guessed by my previous post, I’ve been playing with selenium more and more of late. I totally forgot about my JSUnit + Selenium + JUnit post! Since then, Selenium was split into 2 parts: Selenium Core and Selenium Remote Control (Selenium RC). Selenium RC is really nice. As I suspected, it removes the need for the SocketBasedCommandProcessor I had written.

In short, RC comes with a server-side component that acts as the host for the selenium code as well as a proxy. When you connect to it (using the selenium-driver client: DefaultSelenium) and tell it to launch a browser, the server will configure the browser to use the server as a proxy…then open up the browser to [url of app under test]/selenium-driver/SeleneseRunner.html. Since the server itself is acting as the browser’s proxy it will handle all requests for /selenium-driver/* directly and let all other requests go where they were intended to. This makes the browser think that the selenium code is sitting right along-side the application under test and side-steps the same-origin-policy. Pretty Sweet.

With Selenium RC you can have completely separate Test Projects. The application under test doesn’t need to have a single reference or artifact of selenium in it. You could also use it to write automated scripts that will do some task on a website. For example, you could probably write a simple Swing-based wordpress publishing tool…then write your posts in it…and click ‘Post’…then it would login to your site and publish the post for you.

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?

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

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.

:scriptEnabled

Thursday, January 12th, 2006

I was just reading a little walk-through on styling a select box and it got me thinking about “What if css was enabled, but javascript was disabled?”. Granted, his solution does get around the problem (he only hides the selects that have a classname that is set by javascript…so if you don’t have js enabled, you still see the select). Anyway, I was wondering if there could be a more generic solution to styling things differently based on whether scripting was enabled. Would a :scriptEnabled pseudo-class be a good idea? Obviously we can’t do that, but we could have a scriptEnabled css class that gets slapped onto the document.body element by a bit of script. Then our javascript-assuming styles could be written as:

body.scriptEnabled select{
display:none;
}

I like the idea. Now, is that mixing style and behavior too closely? Maybe, but I still like it. Proceed with caution though…I wouldn’t want to wind up over-doing it and doubling all my rules…one for .scriptEnabled, and one without.

Parsers…

Friday, November 4th, 2005

I’m burnt a bit. Need a break. I think I have a basic idea of how I want to proceed. Basically just a css parser (ast tree output) and the html parser with the visitor pattern. Visit each node and traverse the AST tree for all matching css rules…for each match append an annotation to the html node. Then have another pass that will actually generate the output. At least as a start.

I’ve been looking at ANTLR quite a bit and I’m pretty impressed. It looks like ANTLR 3 will use the StringTemplate ‘engine’ for generating the actual code. The idea is that you could feasibly have 1 grammar and multiple output templates to render the grammar in different languages. Exactly what I was looking at maybe having to write…thank god because it looks like they know a hell of a lot more about lexers/parsers/compilers than I do…and I like where they are taking it (MVC separation). So I may evenually have 1 css grammar that would generate a parser for java, jsp, perl, javascript, php, ruby, python…etc. Awesome.

I also found it interesting how closely css syntax resembles the syntax used in the grammars and the string template files…

CSS Parsers

Thursday, November 3rd, 2005

So I was beginning to think I was going to actually have to write my own css parser…then I found 3 different .jj grammar files (for javacc) that I should be able to bend to my will. One of them is actually used for the w3c’s css validator. I also found a promising html parser too (also javacc generated). It implements a nice visitor pattern as well as supporting annotations on the nodes…so I can write a visitor that will visit each node and leave annotations indicating what css rules matched…then visit it again with a visitor that will actually generate the merged file. Better than what I’d originally thought I’d do…with the added benefit of not requiring strict xml conformance in the markup file.

First Test Case for Stitch

Wednesday, November 2nd, 2005

public static final String simpleCds = “p{ctrl-content:$test;}”;
public static final String simpleHtml = “<html><p>Mock</p></html>”;
public static final String simpleResult = “<html><p>Hello World!</p></html>”;
public void testReplaceByTagName(){
View view = new View(new StringReader(simpleCds), new StringReader(simpleHtml));
Map data = new HashMap();
data.put(”test”, “Hello World!”);
StringWriter out = new StringWriter();
view.render(data, out);
out.flush();
String val = out.getBuffer().toString();
assertEquals(”View got invalid output.”, simpleResult, val);
}
Green baby green…you can imagine how ugly the actual impl is (hint: not parsing anything). I dug around the net a bit and stumbled onto a w3c page on SAC (Simple API for CSS). They modeled it after SAX…seems like a good place to start.