Archive

Archive for March, 2008

Book Reviewed: JavaScript: The Definitive Guide by David Flanagan

March 26th, 2008

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 has been reviewed by a couple web Gurus (Douglas Crockford, Peter-Paul Koch).

JavaScript is 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 itching to push the web browser envelope, to really innovate, then this book is a required read. In addition if you’re coming from a staticly type background like Java or .NET, then JavaScript (a functional programming language) will open your eyes to a different programming model. Once you grock the fundamentals of JavaScript you’ll never be able to look at classical languages (Java, C++, .NET, …) with a straight face again. I highly recommend this book to any web developer from any web framework camp.

View my review on Amazon.

A Completely Normal Post: Our Dog

March 20th, 2008

My blog posts tend to be obscured in programming languages, and techie gibberish, I thought I'd do a normal post on our dog – after all, pets are what blogs are really about, right? :)

Steph (my wife) and I had been toying with the idea of getting a dog, we've been looking at different breeds, visiting shelters, and emailing breeders – I have to give Steph all the credit, she did most of the research. Anyhow, we came across a post on our Kijiji for a mature Soft Coated Wheaten Terrier. Now we have a dog.

Being a Geek and all, I wasn't sure if I was a dog (or cat person), but Belle is a great dog. Her constant need for a walks is a great reminder to take a micro break while working from home.


Belle, our dog.

Author: Adam Kahtava Categories: Calgary, Personal Tags:

Namespacing Your JavaScript

March 17th, 2008

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.

Author: Adam Kahtava Categories: AJAX, JavaScript, Software Tags:

Inter / Cross Browser Window Communication Using JavaScript

March 11th, 2008

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');

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

// Let us 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.

Author: Adam Kahtava Categories: Firebug, JavaScript, Software Tags:

Something About the Cobbler's Children Having No Shoes

March 8th, 2008

As knowledge workers, software developers and the like, we often find ourselves heads down in the trenches (micro focused, working towards deadlines), while throwing self-improvements and work environment improvements to the sidelines.

As the old phrase goes: “The Cobbler's Children Have No Shoes” – the Cobbler was so busy with other peoples shoes, that he couldn't make shoes for his children. Like the Cobbler I often find myself burried in work, and neglecting the things that could improve my situation.

A couple personal examples: this website (the design has remained unchanged for the past couple years), my desk setup (the mountain of books for a monitor stands and a single 17″ monitor) demonstrate this.

I've since purchases an Ergotron LX Dual Desk Mount Arm, and will soon be upgrading to these Samsung SyncMaster 226BW 22″ monitors, which I plan on running in portrait mode.

How can you improve? What does your desktop look like?

 

Author: Adam Kahtava Categories: Musings, Personal Tags:

The summer of ’99: Junior-Style / Newbie Programming

March 1st, 2008

Steve Yegge discusses junior-style programming in his post: Portrait of a n00b. After reading Steve’ post I decided to dig up some of my own newbie code – this code is from the summer of ’99.

I got my first real C++ book
Bought it at the local book store
read it ’til my eyes turned red
it was the summer of ’99

I found this code amusing… To keep things short, I included one method, but the entire class implementation is similar – my comments describe almost every facet of what I now regard as relatively simple logic and I’ve completely removed all whitespace.

As Steve puts it:

[I was] making up a temporal narrative in an attempt to carve out a mental picture of the computation for myself. These stories I told myself were a critical part of my mental development as a programmer. I was a child trying to make sense of a big, scary new world. – Steve Yegge: Portrait of a n00b

The code:

 //***************************_Command.cpp_*********************************
 //__Creator:_____________Adam Kahtava
 //__Date:________________June 14, 1999
 //************************************************************************* 

 //-----Implements the init method defined in the command.h header file
 //-----Keywords and Modifiers are initialized into keyword[], and modifier[1-5].
 //-----(Keywords and modifiers are all separated by semi-colons).
 void command::init(char data[]){
   int j=0;
   int len=strlen(data);
     for(int i=0;i<6;i++){
     //this for loop is run 6 times, 1st for the keyword,
            // and 5 times for the modifiers, and increments i.
     int k=0;
     char temp[20]={""}; //sets temp to "" (the default)
     //goes through "data" copying string into "temp",
     // until delimiter ";", '\0' is encountered or until len >= j 
     while((data[j]!=';'&&data[j]!='\0')&&len>=j){
       temp[k]=data[j]; //copies useful data from "data" to "temp"
       i++; //increments i
       k++; //increments k
     }
     if(i==0){ //is initiated on first "for loop".
       strcpy(keyword,temp); //copies temp to keyword/
     }
     else if(i>0){ //else if "for loop" has been run more than once.
       strcpy(modifier[i-1],temp); //copies temp to modifier[1-5].
     }
     j++; //increments j
   }
 } 

Notable difference from then and now:

Back in ’99 I thought everything I wrote was awesome, I thought I was a Code Poet, or a Programming Ninja (with Real Ultimate Power). I thought my descriptive comments were awesome, and probably thought that by removing all whitespace I would be increasing the program’s efficiency. I thought I could learn more by just programming than reading about programming – I recall discarding books and often hacking my way to comprehension. I was clearly disillusioned.

Today I agree with Jeff Atwood that everything I write sucks, I have an obsession with white space, and prefer to thoroughly understand a programming language before verbalizing my proficiency in it. Now I occasionally get complaints that I’m not including enough comments, and I’m still improving and learning. :)

Author: Adam Kahtava Categories: Musings, Programming Languages Tags: