Saturday, November 25th, 2006

Poly9’s Polyvalent Javascript URL Parser

Category: JavaScript, Library

Denis Laprise and the Poly9 Group needed a robust URL parser in JavaScript, so they created the Polyvalent Javascript URL Parser.

javascript

  1. var p = new Poly9.URLParser('http://user:password@poly9.com/pathname?arguments=1#fragment');
  2. p.getHost() == 'poly9.com';
  3. p.getProtocol() == 'http';
  4. p.getPathname() == '/pathname';
  5. p.getQuerystring() == 'arguments=1';
  6. p.getFragment() == 'fragment';
  7. p.getUsername() == 'user';
  8. p.getPassword() == 'password';
  9.  
  10. p.setURL('another.url.com');
  11. p.getHost() == 'another.url.com';
  12. p.getProtocol() == '';
  13.  
  14. p.setURL('dsdsad'); // throws an exception

This smells like a Java group writing JavaScript to me with the camelCase and thus p.getUsername() instead of p.username.

You can check out the implementation and the test suite (zip).

Posted by Dion Almaer at 9:00 am
33 Comments

+++--
3.4 rating from 31 votes

33 Comments »

Comments feed TrackBack URI

I concur that it seems like a Java group writing JavaScript, but there is a legitimate case for using p.getUsername() instead of p.username — if you want username to be a private member, and to provide only limited, known safe access. That may not be required here (and it may not even be why the poly9 team did this), but the technique itself has uses.

Comment by Anon — November 25, 2006

I felt exactly the same way about they being a group of java guys.

Comment by Marcos Toledo — November 25, 2006

[…] Is Java bad? Ask Ajaxian… [::[ Sat 25 Nov 2006 ]::[ General ]::[ ]::] Ajaxian has once again a new Post about a new Library, this time a URL Parser. All nice and shiny but it isn’t the library I want to write about, it’s the finishing comment they put in there: This smells like a Java group writing JavaScript to me with the camelCase and thus p.getUsername() instead of p.username. Why should it be negative to immitate Java? I’m a Java-Programmer myself and I try to use as much as I can from my experience when writing Ajax applications. I think the Ajax community could learn a lot from the Java style of doing things instead of being so snobbish… […]

Pingback by Fading Roses & Raging Viruses » Is Java bad? Ask Ajaxian… — November 25, 2006

>> Why should it be negative to immitate Java?
Because Java has a tendency to be ridiculously, extremely unnecessarily verbose, as is the case with the above soup of setters and getters. Half those methods would have been enough for a clean implementation. I can guarantee all they do is set an object property anyway. Ridiculously verbose superflous setters and getters *are* a negative programming habit, and definitely not the Javascript way.

If you need further proof of their ineptitude:

p.setURL(‘dsdsad’); // throws an exception

Why should that throw an exception? cause there is no dot.com? isnt this a valid url?:

http://localhost/

Comment by Garcia — November 25, 2006

If you really want to barf, however, take a look at the source code. The setters and getters are created dymanically!!!!! o_0

GOOO JAVA!!!

>> I think the Ajax community could learn a lot from the Java style of doing things instead of being so snobbish
Yeah, mostly they should learn how NOT to ever do something as horrible as this.

Comment by Garcia — November 25, 2006

[quote]
If you need further proof of their ineptitude:
p.setURL(’dsdsad’); // throws an exception
Why should that throw an exception? cause there is no dot.com? isnt this a valid url?:
[/quote]
.
No. “dsdsad” isn’t a valid URL, nor is “localhost”. Learn what a URL is: http://en.wikipedia.org/wiki/Uniform_Resource_Locator
.
It’s a good thing the method threw an exception. In a more poorly written API — one that didn’t use property setters that threw exceptions — you might have spent hours trying to figure out what was wrong.
.
[quote]
Ridiculously verbose superflous setters and getters *are* a negative programming habit, and definitely not the Javascript way.
[/quote]
.
One of the reasons developers use property setters is to encapsulate logic related to the setting of a propery, such as validation! It has nothing to do with Java in particular — you can directly access java member variables if they are properly exposed — it’s simply a design pattern that good programmers use.
.

Comment by Mark — November 25, 2006

Dion Almaer, you ought know better than to feed the trolls with a remark as the last one.

Comment by Hans Duedal — November 26, 2006

Ok, some people don’t like criticism, sorry about that. One thing Ajax developers can definitely learn from Java is documentation, clean code, and a standardized approach on how to handle things. I definitely agree that Java may be a bit too verbose, but would you prefer to work with someone who obfuscates their code (like some libraries I’ve seen lately) or someone who tends to be over verbose? I’d go for the last one…
It’s up to you to decide in the end :-)

Comment by Christian Decker — November 26, 2006

Actually on first appearance of the getters and setters, it thought it was because it did lazy parsing with a regexp only when that method is called. Not because it was mimicing Java. But alas I was wrong.

Comment by Oliver Clevont — November 26, 2006

In JavaScript there is a good reason for using accessor methods instead of properties, besides encapsulation: higher order functions. Using methods/functions you can use functional programming patterns like filter and map without having to write extra functions just to access the property.

IMHO using properties for state access is sloppy, regardless of language, and accessor properties in JavaScript/ActionScript/C# is for those who don’t understand the power of functional programming in these languages.

Comment by Theo — November 26, 2006

I find it unlikely that they implemented getters and setters just so it looks like Java. Its a library – managing upgrades to a library is much easier when the interface is a method rather than a property. Optional parameters can be passed, functions can be overridden using an AOP approach. Unit testing is also generally easier (although looking at the tests setup for this I certainly concede properties or methods would have worked).

Comment by wioota — November 26, 2006

Making a dynamic language that “looks like Java” was one of the original intents of JavaScript in order to harness the power of dynamicism along with familiarity of Java (and with some degree of familiarility with C/C++). I don’t think it is bad to look like Java to some degree, but we certainly don’t want it all the way. Using getters is an important design pattern, and until JS2 provides full getter rewriting support (or you can do it with mozilla, if that is all you use), using getters instead of directly accessing properties is often a better pattern to follow. It will certainly be nice when we can access properites with property accessing syntax and writer getter handlers to handle the access as is coming in JS2.

Comment by Kris Zyp — November 26, 2006

Actually, the Getter/Setter function/method names are not exclusive to Java. Neither is “Camel Caps”. Both are used in many other languages… Getter/Setter is the standard way of creating interfaces to the private variables in your objects – its an object oriented design prinicipal that a lot of people use. We use it extensively in our PHP projects and its just good form. With this approach, we can rely on the interface being coded in a certain way. Sometimes, we can even guess how to gain access to the properties of an object WITHOUT having to examine the class.

Im not doubting that Java hasn’t had an influence on the project. Just stating some facts…

Comment by Karl — November 26, 2006

Just to set the record straight, Java stole the camelCase style for class names and field names from Smalltalk.

Comment by Pat Podenski — November 26, 2006

Actually I find this comparison with Java very funny since I never wrote more than few classes in that language, but thanks for the compliment. My aim was rather to create something like Google Maps, which make extensive use of getters and setters (they use camelcase, too). I thought that using the same conventions as the most widely used Javascript API (now 64% of all mashups on programmableweb.com) was the best way to publish it.
Anyway, feel free to cut & paste the regex and access it with integers, this is very minimalistic.

Comment by Denis Laprise — November 26, 2006

All recently post was copied from Dean Edwards’ del.icio.us bookmarket?

http://del.icio.us/9jack9

Comment by Cheng Guangnan — November 27, 2006

Encapsulation of logic is a good thing, and the hiding of unnecessary implementation details is even better. Granted, the behavior of a URL parser is not likely to change a whole lot over time, but if it needed to change public properties would severely limit how easily that could be done. Hide you implementations – not only because they suck – but because you might need that flexibility later. And to bash Java in favor of Javascript is akin to wearing a flashing neon sign that says “I graduated from my Grade 11 CS class and think I’m a developer”.

Comment by Dan — November 27, 2006

Getters and Setters are useless when the variables that they are accessing are public anyways. Nice, clean code and documentation though.

Comment by Andy Kant — November 27, 2006

Getters and Setters are not useless. Javascript is useless, but that’s not the point. If you want to hide your logic you can – if someone wants to abuse the fact that JS exposes all its variables it’s their issue when the underlying implementation changes. It’s the old just because you can doesn’t mean you should scenario. This site seems to go there a lot recently.

Comment by Dan — November 27, 2006

[…] Via Ajaxian redescubro URLParser, una librería JS que se encarga de ayudarnos a parsear una URL. Realmente potente y cómoda de usar. […]

Pingback by URLParser, el parseador de url definitivo - aNieto2K — November 27, 2006

Hi Dan,

I would be curious to hear why do you consider JavaScript to be useless? Do you mean that the whole language does not serve any purpose, that it does not work well enough to suit some particular needs, that it’s slow, that web browsers are useless, that automating web page elements is useless, etc.?

In your opinion, should websites presently using JavaScript use another, better language, or technology? If so, I’d be interested to hear which one.

Finally, do you surf with JavaScript disabled in your web browser (if you use a web browser)?

Just curious

Thanks

Greg Sadetsky

Comment by Greg Sadetsky — November 27, 2006

[…] Some projets: our Notebook Python API, HQQuery, and URLParser, which has quickly sparked interest and even a bit of controversy! […]

Pingback by Poly9 blog » Blog Archive » Leave some code, take some code — November 27, 2006

My comment that “Javascript is useless” was a direct response to the “getters and setters are useless” comment. Repetition creates a nice effect. I obviously use a web browser, and generally do not disable Javascript. That being said, the shortcomings of Javascript are obvious from the past 10 years of people working to get around it’s limitations and hack it to do things it (1) should have done to begin with, or (2) should never do period. It serves a purpose, but it shouldn’t be considered a complete development language. It is, at best, a work in progress. More people move towards treating it as a fully-featured language should drive its development, but it won’t change any time soon. Any language that lacks synchronization primitives is not going to cut it in the real world.

Comment by Dan — November 28, 2006

I didn’t say that getters and setters are useless; I said that getters and setters are useless in this particular context.

Comment by Andy Kant — November 28, 2006

The real problem with this library is not style. It’s that it doesn’t do the whole job of parsing a URL. It just extracts the “arguments” field as one string; it doesn’t break down the arguments into fields.

Look in the test cases. There’s

p.setURL(‘poly9.com/a/pathname?field=value&field2=value2’);

but no following checks, because they can’t extract the values of “field” and “field2”. This thing is unfinished.

Comment by John Nagle — December 12, 2006

I can’t believe that I’m hearing things like “Getters and Setters are useless when the variables that they are accessing are public anyways.” Getters and setters allow the programmer to completely change the implementation without changing the API.. and abstraction is one of the main benefits of OO programming!

Comment by matthew — December 14, 2006

I’ve also written a URL parser, which (IMO) is much leaner and meaner. Check it out:

http://badassery.blogspot.com/2007/02/parseuri-split-urls-in-javascript.html

Comment by Steve — February 7, 2007

Having getters and setters can be a useful way to protect members. You don’t want to set the property on a URL unless it’s a param, and in that case, calling URL.addParameter or url.setParameter would need a setter and a getter to getParameterValues. Since this is a parser class, it should not (and rightly does not) have getters.

Needless to say, the code needs:
* named methods. Anonymous functions are a pain in the neck to debug. Start with the anonymous constructor:
Poly9.URLParser = function(url)
to:
Poly9.URLParser = function URLParser (url)
* don’t do the magic trick with the setters/getters. Makes it very hard to debug/get a stack trace out of dynamically created methods.
* throw an Error, not a string. This makes debugging much easier.
* should use object literal for URLParser.prototype. This makes the code more readable and compact. It’s like having a block that says “here’s the prototype of the object.”

Saying that the code not good because it looks like java is even more ignorant.

I criticize the code and the critics who didn’t do a good job at criticizing the code.

Props to the people for putting this code out there and letting us all criticize it.

Wow, I’m a latecomer to this post…

Comment by Garrett — May 21, 2007

ajaxian tho. browsers already have these methods implemented natively on Location objects. but you can’t create a location object without setting window.location (and changing the page). really?

Comment by carmen — July 9, 2007

Getters and setters are fine, but why on earth aren’t they using NATIVE javascript getters and setters? I sure as hell like

Myobject.myvar=5;
alert(Myobject.myvar);

MUCH better than

Myobject.setMyVariable(5);
alert(Myobject.getMyVariable());

Javascript has the great ability to make getters and setters completely invisible, and look just like normal variable assignments. Why on earth would you choose to not take advantage of that feature, and save yourself some damn typing?

Comment by Breton — August 24, 2007

Not to mention that it makes shifting from a naked variable to an abstracted variable piss easy, contrary to the comments above. In JAVA you have to start out with getters and setters. in javascript you can switch back and fourth between regular variables and getter/setters without any issue.

Comment by Breton — August 24, 2007

Breton, your statement “Javascript has the great ability to make getters and setters completely invisible, and look just like normal variable assignments” is not entirely correct. This is only possible in Mozilla’s javascript engine.

Comment by Crescent Fresh — October 23, 2007

it doesn’t seem to support ports IE: http://localhost:8080/haha/ha.ha

Comment by ntulip — November 12, 2008

Leave a comment

You must be logged in to post a comment.