RSS 2.0
Journal / Blog
Sunday, June 08, 2008
Book Reviewed: JavaScript: The Good Parts by Douglas Crockford
Weighing in at 140+ pages of content, JavaScript: The Good Parts [Douglas Crockford] cuts through the obscurities, pleasantries, and filler found in most technical books. Instead, this book dives straight into the heart of the JavaScript language. It presents the clearest comprehensive explanation of what makes JavaScript a great programming language that I've encountered to date. It nails the important concepts, like JavaScript's: object oriented nature, its classless (pseudoclassical) nature, and functional nature. While covering the fundamentals like JavaScript's: functions, lexical scoping, lambdas, prototypal inheritance, and functional inheritance.

This book's size makes it approachable for all audiences, its style is terse and concise. This book has the potential to do for JavaScript, what Richie's inspirational classic the C Programming Language did for the C language.

JavaScript is the programming language of the web (AJAX), and this book will guide you through the good parts of this often misunderstood language - while this book is an excellent reference, it is not intended to replace JavaScript: The Definitive Guide, you'll do best to have both these books on hand.

If you enjoyed (or are considering) this book then you may want to learn more of what Douglas Crockford has to say, check out his great JavaScript video series on the YUI Theater.

I highly recommend this book. View my review on Amazon.

Saturday, June 07, 2008
Writing a Control for the AJAX Control Toolkit: Something Stinks
One of my resolutions this year was to contribute to the AJAX Control Toolkit for the ASP.NET AJAX Framework. I began my AJAX Control Toolkit development quest by digging into the online resources, reading ASP.NET AJAX in Action, and decomposing the AJAX Control Toolkit. I noted the huge learning curve required to developing a control, and continued to dig deeper. Once mired in ASP.NET AJAX a bad smell kept wafting by. Since then I've been trying to distinguish this smell.

What's really wrong with ASP.NET AJAX? What's that bad smell?
  • It doesn't plan for performance from day one
  • It treats AJAX as a classic computer science problem
  • It tries to turn JavaScript into a classical language which works against JavaScript's dynamic, prototypical nature
A Case Study: Why Plaxo.com Almost Failed
In the video: High-performance JavaScript: Why Everything You've Been Taught is Wrong (YUI Theater) Joseph Smarr discusses the challenges and lessons learned while developing Plaxo.com. While developing this AJAX centric application, the Plaxo team decided to include everything they could think of (including the kitchen sink) into their application. They created a framework to treat JavaScript as a classical language, they gave priority to features over performance, and... the project ALMOST FAILED. They were able to salvage their application by diverting their development efforts, making performance one of their top priorities, by unlearning everything they'd been taught about classical applications (instead embracing JavaScript), jettisoning unneeded framework bloat, and more.

Some of the points made in this video were:
  • Plan for performance from day one
  • AJAX is not a classic problem
  • JavaScript is not a classical programming language
  • User experience and a responsive application can make or break an application
  • Unneeded bloat in a framework, and an obtuse approach to using AJAX (treating AJAX and JavaScript as a classical language or classic computer science problem) has the potential to cripple your application
This Channel 9 video also mirrors these sentiments: Douglas Crockford, Alex Russell and Joseph Smarr: On the Past, Present and Future of JavaScript
How ASP.NET AJAX Failed: What can we learn from Plaxo?

The way the Plaxo team approached their application development is similar to how the ASP.NET AJAX Framework has been designed. Like Plaxo's initial attempt ASP.NET AJAX attempts to mold JavaScript into a classical language, and attempts to treat JavaScript and AJAX as a classic computer science problem by heaping on more abstractions. Like Plaxo's initial attempt ASP.NET AJAX also gives a low priority to performance. Plaxo was able to change their direction and salvaged their application, but the ASP.NET AJAX Framework is not in a position to make any sweeping changes - ASP.NET AJAX is going down the wrong path and it's too late.

The ASP.NET AJAX Framework is probably another exercise in Framework Architecture (Demoware) and a failure in practice. Its lack of use in the wild attests to these shortcomings - contrast the sites using ASP.NET AJAX with the sites using jQuery (Actions Speak Louder Than Words). Furthermore the places that ASP.NET AJAX does thrive (the small internal ASP.NET business apps that need some bling-bling) will also be the areas that Silverlight shines - Silverlight offers a better Microsoft centric programming model (less leaky Win Form / Web Form abstractions) that most Microsoft developers will embrace. Silverlight will probably divert the developers that currently embrace ASP.NET AJAX.

I don't recommend the ASP.NET AJAX Framework and won't be contributing to the AJAX Control Toolkit. My time is better spent elsewhere.

Tuesday, June 03, 2008
More on the perils of The ASP.NET AJAX Framework
There's no need to whip a dead horse (I've probably been griping about the ASP.NET AJAX Framework for too long), but... Jon Galloway and a group of other notable gurus (K. Scott Allen, Scott Koon, and Kevin Dente) have started a podcast, their latest segment sparked my interest since it covered ASP.NET AJAX and AJAX Libraries / Frameworks in general.

I share their sentiments so I thought I'd post a brief but choppy transcript:
[ASP.NET AJAX] ... does offer some some nice features, they did try to take some of the common pieces of the CLR that [.NET Developers are] used to working with and move that down into a JavaScript library. So you get classes like a WebRequest class that wraps the XMLHttpRequest ... and they have a StringBuilder, and they added methods that we're more accustom with ...

that's wonderful, but I don't find myself needing those extensions all that often. If you want to do strictly client-side programming then something like jQuery offers you a lot more capabilities to do things that you really want to do client-side like sorting and CSS selectors. ... That stuff is easy to do with an Update Panel and ASP.NET, but Update Panels aren't always the best solution to use. ...

the goals with ASP.NET AJAX was to integrate into the ASP.NET server-side model ... that's great for ASP.NET, but it needs more client-side features. ... It works if your thinking from the ASP.NET control perspective, but if you look at it outside the ASP.NET model there are a lot easier ways to do it. ...

ASP.NET AJAX [development] seems to have come to a standstill I'm not seeing a lot of development in that area and the rest of these [AJAX] Frameworks are doing monthly releases. Every month that goes by [the ASP.NET AJAX Framework] falls further and further behind ... it needs to evolve.
Listen to this great podcast here: Technology Round Table Podcast #2 - AJAX Frameworks

Saturday, May 31, 2008
The Good Parts of The ASP.NET Framework and Visual Studio
Douglas Crockford opens his latest book with these words:
Most programming languages contain good parts and bad parts. ... [the language designers or architects] are usually powerless to do anything except heap more features on top of the existing pile of imperfections. And the new features do not always interact harmoniously, thus producing more bad parts. - JavaScript: The Good Parts by Douglas Crockford
His words can apply to all programming languages and frameworks. Especially the ASP.NET Framework and Visual Studio.

Bad parts in the ASP.NET Framework and Visual Studio:
  • ASP.NET Themes and Skins
  • The ASP.NET AJAX Framework
  • ASP.NET / Visual Studio Inline Style Properties
  • Visual Studio Design View
  • ASP.NET and Visual Studio's over dependency on XML configuration files
It would be great if someone wrote a book outlining the good parts of ASP.NET and Visual Studio. :)

What bad parts do you steer clear of?

Saturday, May 24, 2008
Getting a Job at Google: A Web Developer Fizzbuzz
Back when the web turned 2.0, AJAX was all the rage, and gas was cheap, a Google recruiter contacted me. We worked through a couple screening interviews - I explained how I was a .NET / ASP.NET / C# developer with some experience with Java and PHP, I described how C# was somewhat similar to Java. Things went great, I moved on to the next step of the process - writing code (a JavaScript widget for Gmail) with a 2 day (weekend) hard deadline. At the time I was wearing JavaScript diapers, but tried the exercise anyways - I'm still convinced the recruiter confused my Java / C# experience with JavaScript. Anyhow...

The Google Web Developer Exercise:

Web Developer Exercise

Attached are three states of a new contacts widget. This widget will be used across Google and may be anywhere on the page. Designers will also use this in mocks for usability tests. Create the HTML, CSS, and JavaScript for the widget as described in the image. Your solution must work in Firefox v1.5+ and IE v6+. Bonus points for a solution that degrades nicely on older browsers.




After my first attempt, I concluded that:
  1. My JavaScript knowledge was embarrassing
  2. Dynamic programming languages like JavaScript using prototypical inheritance were awesome - as a monocultured .NET developer I had sorely been missing out
  3. Framework Web Developers (ASP.NET, Ruby on Rails, and so on) aren't really Web Developers - we depend on a framework (an API) as a crutch, where the law of Leaky Abstractions is very real, and often when it rears it's head we use our golden hammer (our multipurpose language of choice), but there are better tools at hand
  4. Web Developers claiming n years of experience need to at least know JavaScript, CSS, HTML / XHTML, a server-side language, and some XML / XSL - NOT just a single multipurpose language or framework
  5. Innovation can only happen when you become one with the technologies surrounding your realm - for example: Jesse James Garrett probably would not have publicized AJAX had he been an exclusive ASP.NET developer, David Heinemeier Hansson would have never created Rails had he been an exclusive ASP.NET developer, and Scott Guthrie would never have developed ASP.NET had he been an exclusive ASP.NET developer. Diversity is essential for innovation
In retrospect this exercise is brilliant, it's a more complex derivation of a Fizzbuzz exercise, which effectively weeds out the knowledgeable candidates from the n00bs. JavaScript is notorious for being one of the world's most misunderstood language, many developer (and the ASP.NET Framework) still use JavaScript techniques from the old days of Netscape. For example: <a onclick="return false;" ..., or <a href="Javascript: do something;" ... are common DOM Level 0 inline techniques that should be avoided. These techniques have been replaced, but finding developer that use these JavaScript techniques can be hard.

By having a developer complete this exercise you effectively determine that the they understands these concepts:
  • Cross browser compatibilities and work arounds for both JavaScript and CSS - with a preference given to feature detection (object detection) vs browser detection, an understanding of the different event handling models between browsers
  • An understanding of the separation of concerns - JavaScript, markup, and CSS should be separate files, or at least separated within the document
  • Event registration and listening - DOM events, the different browser event models, no inline level 0 event declarations, no pseudo JavaScript protocol inline declarations within markup
  • An understanding of functional languages - closures, namespaces, lambdas, recursion where necessary
  • Node manipulation - creating, swapping, removing elements
  • Knowledge of non-obtrusive JavaScript techniques
  • Importance of modular / compartmentalization of CSS and JavaScript - defensive programming techniques that minimize the risk of interfering with other scripts and elements within the page, part of the non-obtrusive techniques, how to avoid global variables
  • An understanding on how to debug JavaScript from both IE (link) and Firefox (link)
  • JavaScript code conventions - naming conventions, statement conventions
  • CSS naming conventions
  • General DHTML / AJAX techniques - showing and hiding elements
  • A gauge on their attention to details and UI design intuition - what their gut tells them to do when things aren't spelled out
My latest crack at the Google Web Developer Exercise:

You'll have to visit my site (view this blog post outside a RSS reader) to view the code in action.

The code: GoogleExercise.js, GoogleExercise.html, GoogleExercise.css

Today I'm wearing JavaScript training wheels - feel free to comment on the code, I'm always looking for improvements and suggestions. I did take a couple shortcuts on the CSS / UI side of things as I was focusing more on the functionality.

Using one of the AJAX Libraries (like jQuery) we could certainly do this exercise in significantly fewer lines of code.

Today I still think about Getting that job at Google, Yahoo!, Amazon, or Microsoft. How well do you know JavaScript?

Thursday, May 15, 2008
Actions Speak Louder Than Words: Goodbye ASP.NET AJAX
An anticlimactic conclusion about the ASP.NET AJAX Framework - this framework's niche seems to be the internal (intranet) business application realm that depend on ASP.NET Web-Forms. These applications have a handful of users, a couple developers, no performance or bandwidth requirements, little ambition for future growth, and the developers typically embrace dragging & dropping controls in Visual Studio. In this case the ASP.NET AJAX Framework provides some eye candy, and patches the broken Web-Form metaphor by cramming AJAX into the ASP.NET model, but then comes along the ASP.NET MVC Framework, Silverlight, WPF and ... ??? Goodbye ASP.NET AJAX!

Interesting observations:
How many applications explicitly state that they use the ASP.NET AJAX Framework?
  • 25, this includes sites like DotNetNuke (with a reputation of being slow), view the list here.
How many of these applications are relatively high-traffic?
  • None. ZERO!
How many applications explicitly state that they use the YUI AJAX Library?
How many of these applications are relatively high-traffic?
  • Quite a few. A couple notable sites: Flickr, Slashdot, Linkedin, Paypal, O'Reilly, My Opera.
How many applications explicitly state that they use the jQuery AJAX Library?
  • 516, view the list here.
How many of these applications are relatively high-traffic?
  • Many. A couple notable sites: Twitter, Digg, Dell, Slashdot, BBC, Netflix, Technorati, New York Post.
If no high-traffic application uses the ASP.NET AJAX Framework then why would you? Actions (or lack of action) often speak louder than words, and it appears that the ASP.NET AJAX Framework is not suitable for the real world.

Monday, April 21, 2008
The ASP.NET AJAX Framework is for DUMMIES!
The ASP.NET AJAX Framework is an embarrassing server-side centric approach to DHTML / AJAX web development. While most programming languages and frameworks come with both good and bad parts, the ASP.NET AJAX Framework is probably an example of an overall bad part of ASP.NET - on the contrast the ASP.NET MVC Framework looks to be a good part.


What's wrong with the ASP.NET AJAX Framework?
1 .NET Developers are DUMMIES!
The ASP.NET AJAX Framework appears to have been designed under the assumption that .NET developers are dummies and can't learn or don't want to learn JavaScript. That .NET Developers would rather hobble along with their familiar languages, then to learn something new. I understand that the ASP.NET community's only real problem is education, so let's ask: What is wrong with the ASP.NET Community? Then educate ourselves rather than becoming the .NET Developer statuesque. It's patronizing to use a framework that assumes learning a new language is beyond our capabilities. Many of these other programming languages also happen to be more expressive than the statically typed .NET languages.

2. The "don't write a line of JavaScript" abstraction leaks like a sieve
The Framework is intended to shelter .NET Developers from the big bad JavaScript language. Which, like driving a car across North America without knowing how to pump gas, stops you dead. Either you depend on someone to pump your gas - depend on something like the ASP.NET AJAX Control Toolkit and the many authors to write your JavaScript - or you stop moving. As Web Developers, sooner or later learning how to pump your own JavaScript becomes a mandatory skill.

3. Client-side programming from the Server-side is a absurd
The AJAX Framework does back flips to translate server-side code into JavaScript, and then requires that you write JavaScript anyway. Save yourself the pain, learn JavaScript. One day The Law of Leaky Abstractions comes into play, the gas station attendant fills your gas tank with diesel - your AJAX Control Toolkit blows up (requires debugging) so you have to learn JavaScript anyways.

4. Bloated, poor performance, bad user and developer experience
The AJAX Framework extends many of the native JavaScript objects as it attempts to turn JavaScript into a staticly typed programming language, and tries to hook into the ASP.NET life cycle, but all these features are unneeded as they are ALL already achievable through the native JavaScript language - if it walks like a duck and quacks like a duck, then... err... could someone remind me why we need typed languages in a web browser? Anyhow; all these object extensions, enhancements, and upgrades, contribute to more scripts that need to be downloaded and increases the number of scripts running in your browser. Then to make matters worse there's partial-page rendering and Update Panels which do full page post backs under the guise of AJAX -bad-bad! Client-side scripting is supposed to enhance the user experience not make it worse. Other AJAX Frameworks are built with performance as their number one goal, but in the ASP.NET AJAX Framework. Adding more widgets to JavaScript seemed to be the first priority, and performance an after thought.

5. Working against the grain is a waste of time
The AJAX Framework works against the grain, it would be nice if it embraced the JavaScript language. Very few of the concepts and metaphors used in the ASP.NET AJAX Framework transcend AJAX techniques or frameworks - your time is probably better spent learning how JavaScript works or how the other AJAX frameworks work.

6. Disconnected from the ASP.NET MVC Framework
The ASP.NET MVC Framework throws the ASP.NET life cycle away leaving more dead weight ASP.NET AJAX Framework script and rendering many of the AJAX Framework techniques moot.

7. The ASP.NET AJAX Framework almost over looks the 'J' in AJAX - 'J' stands for JavaScript, and that is GOOD
JavaScript is the glue of the web, even the ASP.NET Framework depends heavily on JavaScript, it is not something to shy away from.

8. Aside from local intranet sites, no one really uses the ASP.NET AJAX Framework.
The AJAX Framework isn't widely used. The ASP.NET AJAX site showcases 25 sites using ASP.NET AJAX. None of these applications appear to be high-traffic or moderately high-traffic applications. On the other hand, the YUI site showcases 89 sites, out of these sites, 6 sites (flickr, Slashdot, Linkedin, Paypal, O'Reilly, My Opera) could be considered high-traffic. Other AJAX libraries like jQuery, and Dojo compare similarly. Your time might be better spent learning one of the other AJAX frameworks.
If we (.NET Developers) are going to claim we know AJAX, then let's focus on the core of AJAX (JavaScript) and stop obscuring it in poor frameworks. Frankly the ASP.NET AJAX Framework is embarrassing, the web development community is laughing at the ASP.NET AJAX Framework and the Developers touting it.

Sunday, April 20, 2008
Book Reviewed: ASP.NET AJAX in Action by Alessandro Gallo, David Barkol, Rama Vavilala
The authors of ASP.NET AJAX in Action did an OK (Average) job at presenting the ASP.NET AJAX Framework. However; this book lacked objectivity and suffered from hype. The authors didn't seem to have proficient experience with the JavaScript language, or enough experience with other AJAX Frameworks / Libraries, or sufficient experience using the ASP.NET AJAX Framework in real world projects. This book sadly felt like most technical books - average.

Comments like "we recommend that...", "because it makes no sense...", "you must rely on a special method...", "you must understand X,Y,Z to run complex client-side code without writing a single line of JavaScript" were discouraging. Many of the "whys" were left answered and the technical inner workings of the framework often trivialized. Don't get me wrong, writing a book is incredibly time consuming, but if you're an author, presenter or the like, and you don't fully understand something then admit it. Do some research, provide some links, or move on. Consistently making comments like these bring the integrity of the whole text into question.

The ASP.NET AJAX Framework itself is technically flawed, bloated, and almost entirely impractical. I was disappointed with the server-centric approach that both the book and ASP.NET AJAX Framework takes. I was disappointed that the book continually pushed JavaScript under the carpet as magic and at the end of the book I was pleased to see the promise of making "the JavaScript code disappear" never was  fulfilled. JavaScript is the very most important part of AJAX, without the 'J' in AJAX, we're left with nothing - just 'Asynchronous', 'And', heaps of more ugly 'XML'.

When reading this book, take the contents and the ASP.NET AJAX Framework with a grain of salt, if you're really serious about learning AJAX then read JavaScript: The Definitive Guide by David Flanagan.

I typically only contribute positive reviews, but I don't agree with the majority of reviews found on Amazon and hope this review provides some objectivity. I commend the authors on their hard work, I'm probably being too harsh with this review - I know it's tough to write a book, and imagine they made many sacrifices as they worked towards tight deadlines.

View my review on Amazon.

Wednesday, April 09, 2008
The ASP.NET AJAX Learning Curve
The ASP.NET AJAX framework comes with a lot of baggage err... I mean... a huge learning curve when compared to other AJAX Frameworks like JQuery, YUI, Dojo, Prototype / Scriptaculous.

Here's a running list of the technologies, and concepts you'll encounter when digging into ASP.NET AJAX:
  • ASP.NET
    • The Page Life Cycle
    • The Control Life Cycle
    • Web Controls
    • User Controls
    • View State
    • Session State
    • Events
  • .NET / Classical Language
    • Interfaces
    • Inheritance
    • Delegates
    • Multicast Delegates
    • Assemblies
    • Properties (Get / Set)
    • Constructors
In addition to these, you also have the technologies universal to all JavaScript libraries:
  • JavaScript:
    • Closures
    • Object Literals
    • JSON
    • Events
    • DOM Manipulation
    • Prototypical Inheritance
    • Constructors
    • XMLHttpRequest
  • Cascading Style Sheets (CSS):
  • Web Services
The ASP.NET AJAX Framework is more complex than other AJAX frameworks, I'm continually lost in it's ambiguity as it attempts to skirt around the JavaScript language - I think this learning curve (and all it's confusion) is precisely why Silverlight has so much potential.

I'm still diving into the low-level details, but my first impressions of the ASP.NET AJAX Framework are:
  • Obscure, ambiguous, no clear vision - it offers multiple (resource intensive) ways to avoid writing JavaScript, but then requires that you write JavaScript anyways
  • Too server centric
  • Too heavy weight (I'm not appreciating how they're trying to turning JavaScript into a Java, C#, .NET clone, the overhead within the browser for these conversions seems like a huge performance bottleneck)
  • Has the potential for poor performance
Most of the other AJAX libraries have been written with performance, browser responsiveness, and User Experience as their number one priorities - I'm still not sure about ASP.NET AJAX.

How many ways can we try to avoid writing JavaScript? If an AJAX library doesn't enhance the User Experience then why use it? Regardless, I'm still digging deeper.

Wednesday, March 26, 2008
Book Reviewed: JavaScript: The Definitive Guide by David Flanagan
JavaScript: The Definitive Guide by David Flanagan is a great book! When I began reading this book I was convinced that (like many technical books) the first couple chapters would contain the important stuff and the content would slowly digress into page filler, fluff, and the book would become just another monitor stand. But not this book! After finishing the formal chapters I started reading the references - YES, this book is so good I'm reading the references! Flanagan has raised the bar for all JavaScript books - this book is in its 5th edition, and reviewed by some of the greats in the Web Development / JavaScript world (Douglas Crockford, Peter-Paul Koch).

I often think of JavaScript as the assembly language of the internet - most of the current-generation web frameworks make heavy use of JavaScript, CSS, and AJAX. If you really want to understand how ASP.NET or Ruby on Rails really works, how AJAX works, how JavaScript libraries work. If you want to really understand how to push the web browser envelope, and how to really innovate, then this book is a required read. JavaScript (and other functional programming languages) present a different programming model. Once you grock the fundamentals of JavaScript you'll never be able to look at classical languages (Java, C++, C#, ...) with a straight face again. I highly recommend this book to ANY web developer from ANY web framework camp.

This book is now in my Recommended Reading section. View my review on Amazon.

Monday, March 17, 2008
Namespacing Your JavaScript
Namespacing your JavaScript is critical for sites that make heavy use of JavaScript, or sites that use any the JavaScript AJAX libraries (Scriptaculous, ASP.NET AJAX Client Side, YUI, JQuery, ...). It's also a great defensive programming technique - this is another post on JavaScript techniques that I've found useful.

Why Namespaces? Well... :) When a browser loads a document, it loads ALL the JavaScript into the browser. Objects that are not enclosed within a Namespace are Global, and Global Variables are Evil because they run the risk of interfering / overriding / clobbering previously defined objects (variables, functions, etc...). The JavaScript language, in its current form does not have native support for Namespacing . So, as pragmatic developers we realize the need to "Program Into [Our] Language, Not In It" - Steve McConnell, Code Complete 2nd Ed, Chapter 34.4. In the JavaScript language we use Objects to achieve Namespacing - we'll cover this closer to the end of this post.
Don’t limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives ... - Steve McConnell: Code Complete 2nd Ed, Chapter 34.4
An example of when Namespaces could be used: Let's say, we're working on a team of 3 developers, each developer is working on a different widget / component for the same page. So inside our HTML / XHTML document we define and load three different JavaScript files and inside these files we have something like:
In someObscureWidgetJavaScriptFile1.js have:
  helloWorld = function(){ alert('hello world'); };
In someOtherObscureJavaScriptFile2.js we have:
  helloWorld = 'hello world';
In someOtherObscureJavaScriptFile3.js we have:
  helloWorld = { hello: 'hello', world: 'world' };
All these JavaScript files get loaded into the browsers global calling object (window), and each assignment of helloWorld interferes with the previous. When we attempt to reference helloWorld we'll be depending on the order in which the JavaScript files were loaded - if the first file was loaded we'll be able to display the alert, if the later file was loaded first we'll be able to reference a string, and so on.

Back to the topic at hand, How do I create a Namespace in JavaScript.
Note: this approach to Namespacing was recommended and referenced in JavaScript: The Definitive Guide by David Flanagan, other methods of Namespacing can be found on the web (Namespacing your JavaScript by Dustin Diaze outlines an alternate approach). For me, the following seems more intuitive, and is recommended in Flanagan's book - probably, the best JavaScript book written to date.

Ceating a Namespace in JavaScript:
// Create the namespace object.  Error checking omitted here for brevity.

var
myNameSpace;
if (!myNameSpace) myNameSpace = {};
myNameSpace.myPseudoClass = {};
//JavaScript doesn't support classes,
// so let's avoid confusing people and call this a Pseudo Class


// Don't stick anything into the namespace directly.

// Instead we define and invoke an anonymous function to create a closure

// that serves as our private namespace. This function will export its

// public symbols from the closure into the myNameSpace object

// Note that we use an unnamed function so we don't create any other

// global symbols.

(function() { // Begin anonymous function definition

  // Nested functions create symbols within the closure

  function displayMyMessage() { alert(myMessage); }

  // Local variable are symbols within the closure.
  // This one will remain private within the closure
  var myMessage = 'Hello World';

  // This function can refer to the variable with a simple name
  // instead of having to qualify it with a namespace
  function getMyMessage() { return myMessage; }

  // Now that we've defined the properties we want in our private
  // closure, we can export the public ones to the public namespace
  // and leave the private ones hidden here.
  var ns = myNameSpace.myPseudoClass;
  ns.displayMyMessage = displayMyMessage;
  ns.getMyMessage = getMyMessage;

})(); // End anonymous function definition and invoke it
Then outside our namespace we can invoke our methods like this: myNameSpace.myPseudoClass.displayMyMessage();

Read Chapter 10, Modules and Namespaces in JavaScript: The Definitive Guide for a deeper dive into Namespaces and Modules in JavaScript!

If you're still not convinced you need Namespaces and are interested in reading more about the issues surounding Global Data, then you may be interested in reading Chapter 13.3 (Global Data) in Code Complete.

Tuesday, March 11, 2008
Inter / Cross Browser Window Communication Using JavaScript
A quick search on the internet for "Inter Browser Window Communication Using JavaScript" reveals many outdated search results recommending questionable techniques. In the past I've fallen prey to many of these ill-advised suggestions. So... I thought, I'd start a small series on JavaScript techniques that I've found useful.

This post covers Inter / Cross Browser Window Communications using JavaScript.

A common scenario in web applications is: to have Page A open Page B , then have Page A communicate with Page B or vise versa.

One of the techniques floating around the internet suggests that you use Cookies and a JavaScript setTimeout function that listens for the presence of a cookie. So essentially Page A sets a cookie and Page B listens for this cookie and acts on it.

A alternate solution might be to use the JavaScript Browser window.open and window.opener methods. Using these two methods we can achieve inter / cross browser window communication as long as the Same Origin Policy is withheld - a similar approach can be taken for frame and iframe communication.

An example:

// myNewWindow stores the reference to the newly
//   created window, this provides a handle for defining
//   and calling methods in the New Window
var myNewWindow = window.open('about:blank');

// Lets call the alert method in our New Window
//   from this window (the Original Window)
myNewWindow.alert('Hello From Original Window');

// Lets call an alert method in our Original Window
//   from our New Window. So.. Lets use a timer
myNewWindow.setTimeout(
  'window.opener.alert(\'Hello From The New Window\')', 100);
Click here to run this code live in your browser window using a Bookmarklet, or copy the above code into your Firebug Command Line Console.

Sunday, February 17, 2008
Software Ethnocentrism: Staving Off Tunnel Vision
Loosely typed / weakly languages are amazing! But... for myself, coming to this conclusion was like an acquired taste.

Many people appreciate loosely typed languages for the how expressive, elegant, simple, and Zen like they are - and I agree, but I haven't always thought this way. You see; strictly typed (statically typed) programming languages have always been the mainstay of my programming vocabulary, C++, Java, and C# were the meat and potatoes of my programming language diet. I used these languages (strictly typed) because they were familiar, I understood how their compilers, IDEs, and comfortable class-based inheritance model worked. If someone asked me whether I liked C# (insert strict typed language) or JavaScript (insert weakly typed language) I would immediately have given preference to the strictly typed language. Why? Because that's where I felt safe, and that's what I understood - besides who wants to admit they prefer the "weak" language? My preference wasn't based on knowledge or experience it was based on my familiarity with the strictly typed culture.

I was suffering from Software Ethnocentrism.
Software Ethnocentrism often entails the belief that one's programming language or development environment is the most important and/or ... are superior to those of other software developers. Within this ideology, software developers will judge other groups in relation to their own particular development environment or culture, especially with concern to programming language, methodologies, behaviour, customs, and religion.
 - the derived definition (above) is based on Wikipedia's article on Ethnocentrism.
I had the tell tale signs of Software Ethnocentrism:
  • I thought strictly typed language were "the bomb"  - the only viable solution :)
  • I thought Test Driven Development (TDD) and Unit Testing was the panacea
  • I was completely obsessed with refactoring tools like ReSharper and Refactoring
  • I thought my Compiler and IDE were superior
  • and I had complete faith in multipurpose strictly typed languages like C#
Then things changed. I started diving deep into the hearts of weakly typed languages: JavaScript, Ruby, and LISP. Now today, I wonder If the time I spent hung up on strictly typed languages, TDD, and unit testing could have been better spent by expanding my programming vocabulary. If I had only delved deep into the heart of weakly typed languages (like JavaScript, 3 years ago) and grocked the fundamentals of these other languages, then I could have achieved this richer understanding of programming languages that I have today. It's important to note, that i'm not stating that weakly typed languages are better than strictly typed languages or vise versa, only that both have their place, are equally useful, and should be used when appropriate.

Do you too suffer from Software Ethnocentrism? Try staving off this programming language tunnel vision, learn a new type of programming language. It might be a better investment in your time than becoming obsessed over a microcosm (like say unit testing and TDD).

Steve Yegge makes some humorous jabs at the static type culture:
... I think we can conclude that people who rely too much on static types, people who really love the static modeling process, are n00bs. ... Hee hee.
 - Steve Yegge: Portrait of a N00b
... I think there's some mystical relationship between the personality traits of "wakes up before dawn", "likes static typing but not type inference", "is organized to the point of being anal", "likes team meetings", and "likes Bad Agile". I'm not quite sure what it is, but I see it a lot.
- Steve Yegge: Good Agile, Bad Agile

... you have your slob type systems and your neat-freak type systems, and it comes down to personal preference. The neat freaks (Java, C#, C++, Pascal) know damn well that the slobs (Perl, Python, Ruby, JavaScript) are just as productive. Maybe even more so.
- Steve Yegge: Egomania Itself
Cartoon Notes: I took this cartoon from Steve Yegge's blog titled Egomania Itself. It represents the irony of static type languages where everything is a named type - presumably the owner of the property is naming all his objects so he can remember what they are, but in loosely type languages, If it walks like a dog and barks like a dog, I would call it a dog. Read more about Dog Typing er... Duck Typing.