Wednesday, September 03, 2008

Javascript Revisisted

When starting an expedition with a new language, (most) people take time to fully understand and learn it before attempting to program with it. Except with Javascript... almost universally, it invites people to dive in without really knowing it. I'm paraphrasing Douglas Crockford here.

I've found this to be very true. Almost 10 years back I started playing around with html and then CSS. The natural final progression led me to Javascript. I clearly remember going through Thau's Javascript tutorials over at WebMonkey trying to actually figure out what I was hacking. Those were exciting times at the height of the "Browser War" with the DOM coming into its own: MS introducing document.all and Netscape's document.layers. After IE won, nothing much happened for the next 5 years. And Javascript, already considered a toy language back then was more or less ignored.

With the emergence of Ajax all that changed. People actually started taking a serious look at JS. Rahul found a series of videos - The Javascript Programming Language - by the above mentioned Douglas Crockford over at YUI threatre. They are by far the best material on revealing the real javascript and what a wonderful dynamic language it is. It is simple, yet, deceptively powerful. I took notes and here are some language highlights:

Overview
  • A real language - small, so easily approachable.

  • Dynamic - "load and go"... i.e. interpreted + loosely typed.

  • Objects are containers... i.e. HashMaps.

  • Prototypical inheritance - No classes. Inherit directly from objects.

  • Lambda support - Closures. "First lambda language to go mainstream".

Types
  • Numbers - 64-bit floats. NaN is result of erroneous operations.

  • Strings - 16-bit chars. Immutable. == compares string values.

  • null - nothing.

  • undefined - default variable value. Missing object members.

  • Booleans - falsy: false, null, undefined, empty string, 0, NaN. truthy:!(falsy)

  • Objects - everything else. Including functions.

  • Loosely typed != Untyped. Checks at runtime. Any type can be stored in any variable including functions.

Ops
  • == and != do type coersion. Use === and !== instead.

  • && and || return values.

  • foreach (i in object) iterates over ALL properties. Use hasOwnProperty check.

  • Scope - blocks {} don't have scope. Only functions have scope. Variables inside function are not visible outside.

Objects
  • Inherit from other objects.

  • Are an unordered Map.

  • Object literals: {} (Basis of JSON: simple data exchange format)

  • New empty object: new Object() == {} == object(Object.prototype)

  • New members are added by simple assignment. No need for a new class.

  • "Linkage" to "parent" object - Simple inheritance.

  • When setting values, only affects current object. When getting values, access goes "up", if not found in current object.

  • Pass by ref.

  • === is comparison on reference.

  • Remove member: delete object[name]

Arrays
  • Inherit from Object.

  • Indexes are strings (numbers are converted).

  • Array literals: [] (== new Array())

  • delete array[index] leaves a "hole" (value is undefined). Use Array.prototype.splice instead.

Functions
  • Are objects.

  • Inherit from Object and can store name/value pairs!

  • JS function == other language lambda.

  • function foo() {} is equivalent to var foo = function() {}

  • Can have inner functions with access to parent function scope even after parent function is invoked: Closures.

Misc
  • Can augment built-in types by modifying prototypes.

  • Avoid type wrappers (added to be similar to Java).

  • Browser 'window' is global object. Container for all global vars and built-in objects.

  • Every object is a separate namespace.

  • Browser apps are all single threaded.

DOM
  • id - uniquely identifies element.

  • Avoid document.all. Use document.getElementById(id), document.getElementsByName(name), .getElementsByTagName(tagName).

  • Document Tree Structure: document is root. document.documentElement is HTML tag. document.body is BODY tag.

  • Node: child, sibling, parent pointers. childNodes list.

  • Style: node.className/node.style.styleName

  • Events: Browser - event driven, single threaded, async programming model. Events targeted at particular nodes. Events cause invocation of event handlers. (Remove event handlers from nodes before deleting). node["on" + type] = function to add event handler. Event handlers send optional event object. Events bubble up from "specific" to "general".

  • Dialogs: alert, confirm, prompt all block async model. Avoid them in ajaxy apps.


Detailed slides:
The Javascript Programming Langauge
Advanced Javascript
DOM

Thursday, June 26, 2008

Eclipse Ganymede is out


.. and one hungry Indian dude wrote a section in the New and Noteworthy.

Monday, March 31, 2008

Immutable locks

Immutability is something that's mentioned over and over when it comes to parallel programming. Part I of Java Concurrency In Practice is all about composing objects that "play well" in the concurrent world and those that are immutable are the "best" citizens. No wonder functional languages are coming up in a big way. Anyone want to bet on them taking over the world in the next decade? Or if not taking over outright, at least succeeding in mutating our beloved imperative ones into unrecognisable functional beasts.

Anyway, check out the method below:

public class Foo {
    private Listener[] listeners;

    public Foo() {
        listeners = new Listener[0];
    }

    public void addListener(Listener listener) {
        synchronized (listeners) {
            Listener[] newListeners = new Listener[listeners.length + 1];

            for (int i = 0; i < listeners.length; ++i) {
                newListeners[i] = listeners[i];
            }

            newListeners[listeners.length] = listener;

            listeners = newListeners;
        }
    }
}


So here, the first thread to obtain the lock on listeners reassigns it to a new Array object... newListeners. Subsequent threads would continue to lock on the old listeners array, while new threads would lock on the "new" listeners array, and potentially corrupt the data. So I guess there's an unwritten property about locks... they need to be immutable to avoid situations like the above.

So given that locks need to be constant, there's no way to have a workable solution in the above code without using an additional object as the lock. The easy "lazy" thing to do is to just synchronize the method itself. The Foo instance (this) would then be that "additional object". But that would be wasteful since it would prevent all other synchronized method calls, even ones that have nothing to do with listeners.

(If instead of an Array, a List was used, the problem wouldn't have occurred given that the List itself wouldn't change. And I think, nowadays mostly the thinking when programming in managed languages is to go for Collections, rather than mess with manually managing Arrays. But I have still seen code like the above, so it's not totally contrived.)

Sunday, March 30, 2008

Constant Learning with Miro

In every field, it's important to continue to learn about one's discipline even after graduating from formal learning institutions. No where is this more pertinent than in the software industry where the only constant is (fast and furious) change. There's always books and articles to keep up with what's new, but videos have emerged in a big way as another avenue.

And it seems like the developer communities at all the big guns... Microsoft, Sun, Google and Yahoo... have jumped on the bandwagon and are producing great content. Microsoft had started channel 9 a few years back where they'd go around interviewing key engineers. Sun has videos through the Sun Developer Network Channel. Google has their Tech Talks series. Rahul introduced me to Yahoo's YUI Theater few months back.

The great thing about a lot of the talks is that although they are presented in the context of the company's platform/language/technology, they tend to transcend them and are concepts and trends that apply to general software engineering. Microsoft's channel9 for instance, has had wonderful discussions with architects and designers on everything from functional programming to garbage collection to concurrency.

In spite of all the great videos out there, it's a hassle to have to go to each of these different sites, see what's new and watch it. Enter Miro. Miro is an amazing open source application designed specifically to consume vidcasts (it works with podcasts too). Here's a screenshot where I've subscribed to some of these "channels" (yes, I have a lot of catching up to do!).



You may be wondering if this really is a huge deal. I think it is. Miro simplifies and automates the process and makes it so simple and easy. Every time you start miro, it'll tell you of the latest content available and ask if you want to download it. And the quality is generally much better what with being able to view it full screen and it also has nifty features like remembering where you left of in case you have to pause midway through etc... The one downside is that it has to download the video bits as opposed to streaming it through flash (as is common on many sites since the emergence of youtube). So for the bandwidth constrained it can be a bit of an issue. But then again, flash still has some issues on Linux and some of the videos don't play. Plus, looks like Microsoft recently converted to Silverlight which doesn't work on Linux (haven't looked into Moonlight). So most likely you'd end up having to download it anyway.

I've only mentioned few channels, but as you can imagine, there's tons of them around the web. Miro has a guide built-in which showcases some of them. Apart from tech content, many universities like Berkeley and Princeton are broadcasting some of their lectures and events. So there's definitely no lack of content. Just need to make time!

Overall, I love Miro and can't say enough good things about it. Kudos to the guys who've developed it.