Monday, January 31, 2011

Basic JavaScript Part 9: Reusing Methods of Other Objects

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods
  8. Namespaces

In one of my previous posts, I mentioned that functions in JavaScript are plain objects that can have their own properties and methods. One of these methods that are available for every function object is a method named call(), which is defined on the prototype of Function. This method allows you to ‘reuse’ a method from another object. Let’s talk code.Suppose we have an object called podcast which has a download() function:

var podcast = {
    name : 'Astronomy podcast',
    download : function(episode) {
        console.log('Downloading ' + episode + ' of ' + this.name);
    }
};

podcast.download('the first episode');

The output we get by executing this function is exactly what we expect it to be:

“Downloading the first episode of Astronomy podcast”

Now suppose we bring on another object called screencast :

var screencast = {
    name: 'Node tuts'
};

Wouldn’t it be nice if we could somehow reuse the download() method of the podcast object so that we can download a screencast as well. We can do this by invoking call() on the download() method like so:

podcast.download.call(screencast, 'the last episode');

This gives us the following output:

“Downloading the last episode of Node tuts”

What exactly happened here? Well, we just invoked the call() method on the download function object, specifying a reference to the screencast object and a string argument that describes the particular episode. The download() method got invoked with the screencast object bound to this. Therefore, the download() method uses the name property of the screencast object instead of the name of the podcast object.

There’s also another method with similar functionality defined on the Function prototype named apply(). This method behaves exactly the same as the call() method, except that the arguments passed to the underlying method in question need to be passed as an array.

    podcast.download.apply(screencast, ['the last episode']);

Utilizing the call()/apply() methods is a very powerful way to reuse features of objects that are built into JavaScript (like Array, String, etc. …) or from third-party libraries. But I don’t recommend applying this technique when you own the code of the method you want to reuse. A simple refactoring like extracting the particular method into another object is a much better approach.

Until next time.

Wednesday, January 26, 2011

Basic JavaScript Part 8: Namespaces

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods

In my previous post, I showed how you can ‘emulate’ static members in JavaScript without having a dedicated syntax for it. For this post, I’m going to discuss namespaces in JavaScript. In order to reduce the number of objects and functions that are added to the global scope in our applications, using namespaces in JavaScript is definitely a recommended practice. Just like static members, namespaces don’t have any dedicated syntax built into the language either. But we’re able to get the same benefits by creating a single global object and adding all our objects and functions to this object.

var AppSpace = AppSpace || {};

AppSpace.Podcast = function {
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = 'http://www.astronomycast.com';
};

AppSpace.Podcast.prototype.toString = function() {
    return 'Title: ' + this.title;
}

This way we lower the possibility of naming collisions when using our code in conjunction with other JavaScript libraries. We can also use the same naming conventions for namespaces as in any other programming language that does provide syntactical support. Suppose we want to use a namespace like “MyCompany.MyApplication.Model”. We can accomplish this by using the same approach as shown earlier:

var MyCompany = MyCompany || {};
MyCompany.MyApplication = {};
MyCompany.MyApplication.Model = {};

or something like the following:

var MyCompany = MyCompany || {
    MyApplication: {
        Model: {}
    }        
};

However, this approach can become very cumbersome and hard to maintain when our code expands over time. In order to overcome this issue we can use a general purpose namespace function to achieve the same thing using a single line of code.

var model = namespace('MyCompany.MyApplication.Model');

model.Podcast = function {
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = 'http://www.astronomycast.com';
};

model.Podcast.prototype.toString = function() {
    return 'Title: ' + this.title;
}

Here’s an example of how we can implement such a namespace function.

function namespace(namespaceString) {
    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';    
        
    for(var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }
    
    return parent;
}

Using this approach requires less typing and the resulting code also looks less verbose. Some JavaScript libraries, like YUI and the Dojo Toolkit, provide their own implementations for such a namespace utility function. I encourage you to take a look at their implementations as well.

Until next time. 

Friday, January 21, 2011

Book Review – Extreme Programming Explained

Last week I finished reading the first edition of Extreme Programming Explained, written by Kent Beck. I explicitly wanted to read the first edition, that I purchased via AbeBooks, which is also the first book that appeared in the series of books on XP. I’ve read a couple of book reviews of the second edition on the interweb where some have stated that the second version is somehow less ‘extreme’ compared to the first edition. That’s why I went for the first edition as I wanted to learn from the ‘original’

While it seems that Scrum and Lean are getting all the buzz in agile software development these days, why on earth would I want to pick up a book on Extreme Programming that has been written back in 1999? Well, it’s my current feeling that XP is the ‘core’ agile methodology. While there was some buzz around this software methodology in the late 1990s and early 2000s, it has never been commercialized nor pursued by hypesters, at least not on the same scale as Scrum and Lean. I’m not saying that Scrum and Lean are therefore bad and should be avoided. On the contrary! I’ve been part of a Scrum team for many years now where we’ve been complementing this project methodology with XP engineering practices like unit testing, continuous refactoring, continuous integration, etc. … . This has been working because of these XP practices, not the other way around. But what I’m seeing more and more lately are teams that are adopting Scrum without any of these solid engineering practices, especially in enterprise environments. Therefore I think it’s important to learn more about XP, which is one of the agile methodologies that somehow managed to preserve its values throughout these years without losing its balance. I’m with Uncle Bob when he states the following in his blog post on Bringing Balance to the Force

“I, for one, consider the agile movement to have been inundated by a vocal and enthusiastic cohort of project managers, waving their scrum-master certificates, or their Lean and Kanban books.  They have overwhelmed the original movement and changed it into something new.   Agile is no longer about a balance between the technical and non-technical parts of development.  Rather it has become a discussion almost entirely dedicated to non-technical issues.  Agile is no longer about healing the divide, or closing the crevasse.  The agile movement now represents one side of the crevasse.”

Anyway, back to the book review. I personally found this book to be a very fascinating read. It’s divided into three major parts:

  • The Problem – This first section sets the stage for XP. The chapters in this section discuss the value proposition for XP while also showing the disciplines behind it. The four values of XP are Communication, Simplicity, Feedback and Courage while the fundamental principles are Rapid feedback, Assume simplicity, Incremental change, Embracing change and Quality work and the four basic activities are Coding, Testing, Listening and Designing. These values, principles and activities are broadly discussed throughout this section. Basically, here you’ll get a high-level view of Extreme Programming.
  • The Solution – Given the values, disciplines and activities from the first part, the second section elaborates on the strategies and practices that make up XP. The practices discussed are The Planning Game, Small releases, Metaphor, Simple design, Testing, Refactoring, Pair programming, Collective ownership, Continuous integration, 40-hour week, On-site customer and Coding standards. The book doesn’t provide an explanation on how to do these practices. It’s more about why these practices are important and why they’re under the XP umbrella.
  • Implementing XP – The third and final section of the book deals with a number of various topics like how to adopt XP, when to use it, when not to use it and what it takes from people that are part of an XP team. I personally got the most value from the chapters in this section.  

Something that the author kept repeating throughout the book was the importance of how the office furniture is arranged for an XP project team. I never really thought about this, but after reading this book I’ve come to realize how important this can be. Being able to easily pair program and get the customer to sit with you can in fact be a game changer.

Here are some of my favorite quotes that I picked up while reading the book:

“No single action takes the life out of a team or a person more than being told what to do, especially if the job is clearly impossible. Primate dominance displays work only so long in getting people to act like they are going along. Along the way, a person told what to do will find a thousand ways of expressing their frustration, most of them to the detriment of the team and many of them to the detriment of the person.”

“So you code because if you don't code , you haven't done anything. You test because if you don't test, you don't know when you are done coding. You listen because if you don't listen you don't know what to code or what to test. And you design so you can keep coding and testing and listening indefinitely.”

“Code gives you a chance to communicate clearly and concisely. If you have an idea and explain it to me, I can easily misunderstand. If we code it together, though, I can see in the logic you write the precise shape of your ideas. Again, I see the shape of your ideas not as you see them in your head, but as they find expression to the outside world.”

“The difference is between playing to win and playing not to lose. Most software development I see is played not to lose. Lots of paper gets written. Lots of meetings are held. Everyone is trying to develop "by the book", not because it makes any particular sense, but because they want to be able to say at the end that it wasn't their fault, they were following the process. Software development played to win does everything that helps the team to win and doesn't do anything that doesn't help to win.”

I highly recommend that you pick up and read this book. It’s only 166 pages and a bargain on AbeBooks or Amazon. By reading this book I learned a lot about agile software development and more importantly, how to strike a balance in customer collaboration and technical stuff. The book contains a tremendous amount of knowledge and wisdom. I sometimes had a very hard time putting it away as its also very nicely written. Two thumbs up!

Wednesday, January 19, 2011

Basic JavaScript Part 7: Static Properties and Methods

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion

In this post, I’m going to quickly show you how to set up static properties and methods in JavaScript. This can come in handy for constant values and/or utility functions. C# and most other class-based languages have a special syntax for static members. Not so for JavaScript. Although JavaScript doesn’t provide a dedicated syntax for static members, we’re still able to get what we want by adding properties and methods to a constructor function. This is possible because functions in JavaScript are plain objects that can have properties and methods of their own. 

Let’s show some code.

    function Podcast() {};
    
    Podcast.FILE_EXTENSION = 'mp3';
    Podcast.download = function(podcast) {
        console.log('Downloading ' + podcast + ' ...');
    };
    
    Podcast.prototype.play = function() {
        console.log('Playing this podcast ...');
    };

Here we created a constructor function named Podcast with a static property called FILE_EXTENSION and a static method named download. We also added the instance method play() to the prototype of our constructor function.

Getting the value of a static property or invoking a static method is done as follows:

Podcast.FILE_EXTENSION;                // 'mp3'
Podcast.download('Astronomy cast');    // 'Downloading Astronomy cast ...'

When we create a Podcast object and invoke the instance method play(), we obviously get the expected outcome.

new Podcast().play();    // 'Playing this podcast ...'

But it’s surely not possible to statically invoke an instance method like so:

Podcast.play();        // undefined

It’s also not possible to invoke a static method on a Podcast instance object either.

new Podcast().download('Railscasts');    // undefined

There you go. Knowing how to provide static members in JavaScript might come in handy when you feel inspired of writing your own Math class in JavaScript :-).

Until next time.

Friday, January 14, 2011

Taking Baby Steps with Node.js – Debugging with node-inspector

Here are the links to the previous installments:

  1. Introduction
  2. Threads vs. Events
  3. Using Non-Standard Modules

Writing unit tests for your code drastically reduces the amount of debugging. This is the case for practically any programming language that you work in. But when the shit hits the fan, having a debugger with some decent features at your disposal is a must. However Node.js doesn’t come with a debugger out of the box. Thankfully there are a couple of debuggers out there like ndb, node-debug and node-inspector, which I’ll going to be demonstrating in this blog post. For this blog I’m going to show you some of the nice capabilities of node-inspector.

Installing node-inspector is actually pretty easy when you have npm installed. Just issue the following command:

npm install node-inspector

Now we can startup node-inspector …

node-inspector &

which shows the following output if all goes well:

image

 

 

 

 

 

Now that we have node-inspector running, we can start debugging our node.js application in another console:

node --debug server.js

which outputs the port on which the debugger is listening.

image

 

 

 

Now you can open Chrome and point it to the following URL:

http://127.0.0.1:8080/

If all goes well, then we’ll get to see some JavaScript source code:

image

 

 

 

 

 

 

 

 

 

 

 

Note that you’ll have to use Chrome or another WebKit based browser for opening node-inspector. I also tried it in Firefox, but the page doesn’t show at all.

You can then select the JavaScript source file that contains the code you wish to debug and add breakpoints like you would normally do in an IDE like Visual Studio.

Now we can start using our application until we hit a breakpoint.

image

 

 

 

 

 

 

 

 

 

 

 

On the right of the page we can add watch expressions, look at the call stack and the current values of the scope variables. In the code window we have the usual suspects like “Step over”, “Step into next function” and “Step out of current function”. We can even do live editing and all of this right in the browser! Tooltips also work as expected.

image

 

 

 

 

 

 

 

 

 

 

 

Another nice feature is the console window that can be shown/hidden below or taking over the entire window by clicking the menu button at the top of the page.

image

Because I’ve been using version 0.2.3 for developing my very first application using Node.js, I had to install an older version of node-inspector. If you decide to use the latest version of Node.js, you will see that a couple of interesting new features have been added, like heap snapshots. Make sure to watch this short screen cast to get up and running in no time with node-inspector.

Using node-inspector while developing Node.js applications can really save you a lot of grief. It certainly helped me to find a couple of bugs that would otherwise be hard to track down. It’s also a great learning tool if you would like to learn more about how Node.js behaves at runtime.

Until next time.

Wednesday, January 12, 2011

Basic JavaScript Part 6: Automatic Semicolon Insertion

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting

For this post, I’m going to discuss a feature of JavaScript that can easily get you in trouble. Semicolons in JavaScript are not mandatory. This means that if you forget to place a semicolon after some statement, JavaScript isn’t going to complain about it. But most JavaScript engines make up for this lack of consistency by automatically adding a semicolon for you at runtime. This is were you can get in trouble and leave you wondering what is going on. Let’s take a look at the following code snippet:

function shoeFactory() {
    return 
    {
        shoeSize: 48
    };
}

var shoe = shoeFactory();
console.log(shoe);

You might expect that calling this shoeFactory function is going to return an object with a shoeSize property set to the number 48. Wrong! When executing this code, the shoeFactory method actually returns undefined instead of a new object.

What really happens at runtime is this:

function shoeFactory() {
    return;     // Automatic semicolon insertion (returns undefined)
    {    // Unreachable code block
        shoeSize: 48
    };
}

The way to get this code to behave properly in this case is by placing the opening curly brace of the object literal at the end of the line that contains the return statement. 

function shoeFactory() {
    return {            
        shoeSize: 48
    };
}

The placement of semicolons might come off as a matter of preference. But the way you outline braces in JavaScript can be very important for your JavaScript code to behave properly. It’s highly recommended to not rely on the automatic semicolon insertion mechanism and to always try to put semicolons on the right place in the code. Also trying to outline curly braces as shown above can save you some headaches in case a semicolon is forgotten somewhere in the code.

That’s it for this one. Until next time.

Monday, January 10, 2011

The Social Network

Over the weekend I watched this movie called The Social Network. As a geek, I felt that I was somehow mentally obligated to see this movie :-). While I was watching this movie, I noticed a subtle detail that was shown a couple of times throughout the film. This subtle detail showed how this small team of geeks maintained and preserved the productivity and efficiency of their team. Basically, whenever someone barked into a room where geeks were working, team members that were not working or having a break protected their peers that were "in the zone" from any kind of interruptions from this person. So the individual that marched in there wasn’t allowed to talk or interrupt someone that was working. If this individual did try to interrupt a working member of the team, he got told that this person was not available and to leave him or her alone. If the person working somehow still got distracted, the non-working team member reminded him of his responsibility by firmly telling him "you're working", trying to get his peer back to whatever he was doing.

I don’t know whether this is actually part of the team culture at Facebook, and frankly, it doesn’t matter. I just find this to be a cool and fascinating idea. I’m intrigued by this notion of a team that takes responsibility for preserving their flow and velocity, protecting other members of the herd from interruptions and any other kind of events that prevent them from effectively doing their job. Sounds pretty self-organizing to me.

I have to admit that this is also the first time I actually learned something useful from a Hollywood movie. I must say that this feels weird too ;-).

Saturday, January 08, 2011

Book Review – JavaScript Patterns

Book cover of JavaScript Patterns

Earlier this week I finished reading JavaScript Patterns, written by Stoyan Stefanov. After I very much enjoyed reading his previous book titled Object-Oriented JavaScript last summer, I instantly bought JavaScript Patterns when it came out and put it on my priority reading list. While Object-Oriented JavaScript is more an introduction to the JavaScript language and targeted towards folks that are either new to the language or already been using it superficially for some time, JavaScript Patterns  wonderfully succeeds at building on existing knowledge and taking it to the next level.

This book might as well have been titled “The JavaScript Way”. It’s only 200 pages, but literally packed with great concepts and knowledge about JavaScript and is very dense. While reading this book you can easily notice that the author has an immense amount of experience with JavaScript combined with great writing skills.       

The book not only taught me about JavaScript programming. It also challenged the way how I code in other programming languages as well. It made me think about the differences between static and dynamic languages as well as programming languages that have lots of features compared to others that have a more compact feature set but seem to thrive because of their conciseness.

The book has eight chapters. After a short introductory chapter, the author dives right in by laying out a wide amount of JavaScript essentials in the second chapter.

The third chapter discusses Object/Array literals and constructors while the fourth chapter provides in-depth information about functions in JavaScript.

Chapter five and six are real masterpieces. The fifth chapter is dedicated to object creation patterns, explaining private properties and methods, the module and sandbox patterns and much more. Chapter six discusses several ‘classical’ patterns (as in class), ways to accomplish inheritance in JavaScript, mixins, etc. This chapter is also a nice follow-up on chapter six in Object-Oriented JavaScript. These two chapters were real eye openers for me.

Chapter seven provides JavaScript implementations for the Gang of Four patterns, like the singleton, factory, decorator, strategy, mediator, observer amongst others.

Chapter eight is all about programming JavaScript in the browser and manipulating the DOM. I personally found this to be very interesting and good to know, but not that useful. You don’t have to deal with these things anymore as libraries like jQuery are taking care of that stuff for you. Off course, this doesn’t change my view and perception of the entire book. The parts on deploying JavaScript files and the discussion on loading strategies definitely make up for it.      

Summarized, this book is AWESOME and is now part of my list of favorite books. I can only encourage you to pick up this book. It’s definitely not a book for beginners, but if you want to take your existing JavaScript skills to the next level and beyond, then reading this book is highly recommended.