Tuesday, January 24, 2012

Introducing TrackMyRun

I’ve been working on a small pet project for a couple of weeks now, which I named TrackMyRun. I’m quite fanatic when it comes to running, doing about 130 runs a year. Currently I’m keeping track of all these runs in a simple spreadsheet, but off course, that’s certainly not “the geek way”. Hence the start of yet another pet project.

TrackMyRun is written using CoffeeScript, Node.js and Express. I’m also using the Bootstrap toolkit from Twitter for styling. I’m intending to actually use this small application for myself by hosting it on Heroku or some other cloud solution as soon as I’m able to finish the most essential features. It’s far from done yet, but you can already have a look at the source code on GitHub.  As always, suggestions are welcome.

Happy reading!

Saturday, January 21, 2012

Taking Toddler Steps with Node.js - Express Routing

In the previous post I provided a short introduction to Express, a web development framework built on top of connect that is heavily inspired by Sinatra. For this post we’ll dive into a couple of styles for dealing with routes in Express.

Express simply uses HTTP verbs for its routing API.

// Index
app.get('/runs', function(request, response) { });            

// New run 
app.get('/runs/new', function(request, response) { });

// Create a new run
app.post('/runs', function(request, response) { });

// Show run
app.get('/runs/:id', function(request, response) { });

// Edit run
app.get('/runs/:id/edit', function(request, response) { });

// Update run
app.put('/runs/:id', function(request, response) { });

// Delete run
app.delete('/runs/:id', function(request, response) { });

Well, that’s pretty much all that you need to get started. The routes that we specified here are treated as plain old regular expressions. Note that in order to make the put and delete routes work, we have to add a hidden field to the view.

<input name="_method" value="PUT" type="hidden">

But the thing that I personally struggled with the most was finding out a decent way to divide up these routes into separate modules without too much of a hassle. Most sample and demo applications out there that use Express usually have all their routes specified in a single app.js file. This is something that I don’t like very much as this can become unmaintainable faster that you might think. Roughly 2000 years ago, there was this great emperor (and many after him) who valued the principle of Divide and Conquer. In order to create maintainable applications, being able to divide up these routes is quite essential. There are several ways to do this.

Express Resource

This library enables us provide resourceful routing. As usual, express-resource can be installed using npm by using the following command:

 npm install express-resource

Using express-resource, we can create controller modules and use them from our main module. The following snippet shows how a simple controller looks like:

exports.index = function(request, response){
    response.send('Index runs');
};

exports.new = function(request, response){
    response.send('New run');
};

exports.create = function(request, response){
    response.send('Create run');
};

exports.show = function(request, response){
    response.send('Show run ' + request.params.id);
};

exports.edit = function(request response){
    response.send('Edit run ' + request.params.id);
};

exports.update = function(request, response){
    response.send('Update run ' + request.params.id);
};

exports.destroy = function(request, response){
    response.send('Delete run ' + request.params.id);
};

Now in the main module (app.js) we just have to add the following code:

var resource = require('express-resource')

// ...

application.resource('runs', require('./routes/runs'));

That’s it! Now all these routes are hooked up and ready to use. Express-resource has a few other neat features as well. Check out this episode from Node Tuts to learn more.

Although this seems like a good solution to divide up routes into controller modules, somehow it doesn’t resonate with me. All routes for a particular resource need to exist in the same module which still feels a bit unwieldy to me. I want to have an even more granular approach.

Super-duper Require

What I like to do is to separate routes based on their context:

  • runs/index.js ( index route )
  • runs/new.js ( new and create routes )
  • runs/show.js ( show route )
  • runs/edit.js ( edit and update routes )
  • runs/delete.js ( delete route )

Wouldn’t it be cool if we could just “require” the runs directory and hook up all routes exported by all the modules that exist in this directory? Well, meet super_duper_require! While still using express-resource, we can now add all these routes like so:

    application.resource('runs', super_duper_require(module, './routes/runs/'));

This is how the super_duper_require function looks like:

    _ = require('underscore');
    
    function super_duper_require(mod, path) {
        var mixin = {};
          fileSystem.readdirSync(path)
              .forEach(function(filename) {
                _.extend(mixin, mod.require(path + filename));
            });
    
          return mixin;
    };

We just use the magnificent underscore.js library here to hook things up. This is just one of the fancy ways to solve the granularity problem. If we don’t want to use the express-resource library, we can always accomplish the same thing by going “plain old school” style.

Plain Old School

This is how I currently set up routing with Express. We no longer need the express-resource library for setting up our routes, but we can still use the same granularity as shown earlier. We also need underscore.js again, just as in the previous example, in order to stitch things together.

    var routes = require('./routes');
    var routes.runs = _.extend(require('./routes/runs'), 
                               require('./routes/runs/new'),
                               require('./routes/runs/show'),
                               require('./routes/runs/edit'),
                               require('./routes/runs/delete'));
                               
    ...
    
    function bootstrapRoutes(application) {
        app.get('/runs', routes.runs.index);            
        app.get('/runs/new', routes.runs.new);
        app.post('/runs', routes.runs.create);
        app.get('/runs/:id', routes.runs.show);
        app.get('/runs/:id/edit', routes.runs.edit);
        app.put('/runs/:id', routes.runs.update);
        app.delete('/runs/:id', routes.runs.delete);
    }

Up until now I’m pretty happy with this approach. I would love to hear how others divide up their routes into several modules. So please let me know if there are other awesomely cool ways to deal with this. In the mean time, I hope this helps.

Until next time.

Friday, December 30, 2011

Retrospective of 2011, Looking Ahead to 2012

Yep, that time of the year again. Shiny new calendars and the accompanying festivities are upon us again. I can’t get rid of the feeling that every year passes by a lot faster than the year before. This year was definitely not an exception in that regard and I’m afraid that things are not going to improve in 2012.  

Nonetheless, a lot of stuff happened this year, good and not so good. First of all, I changed jobs twice this year. I’ve been working at iChoosr for a couple of months now and it still feels like I’ve finally come home. I really enjoy working there, my colleagues are awesome folks and I learned a ton already. I do hope to have at least the same amount of fun next year.

While enjoying my .NET job during the day, I’ve been doing a lot of Node.js hacking in my spare time, which you could probably tell looking the amount of blog posts I’ve been writing on this topic this year. This has all been a lot of good fun. I have a couple of more blog posts on Node.js lined up for next year, so stay tuned.

The new programming language I learned this year was CoffeeScript, which looks a lot like Ruby. Unfortunately, Ruby is still on my wish list for new programming languages to learn as is Clojure and/or Scala. I wonder which of these I’m going to pick up in 2012?

One of the things that I’m eager to learn about is another operating system. I’ve been soaking in a lot of Unix/Linux stuff during the last couple of months. I’ve been using and developing software for the Windows platform like forever and learning an entire new OS has not been easy. But I must say that it’s well worth the time and effort. I’ve been developing Node.js libraries and applications in my spare time entirely on Ubuntu and I’m looking forward to take a peek at Linux Mint as well. Perhaps I’ll completely switch over to Linux next year, I’m not entirely sure about that yet.

I’ve been facilitating a good number of European VAN sessions throughout the year. 2011 has been the third year for the E-VAN and I must say that it’s been a fun ride. But I do feel that the time has come for me to move on. I must admit that I only opened Visual Studio a couple of times in my spare time, and then only by accident. Being really honest with myself, I’m just not that interested anymore in the latest and greatest in the .NET space compared to only a couple of years ago. I think I somehow hit a saturation point. So I’m no longer going to organize and/or host new E-VAN sessions. I’ll be more than happy to pass the torch to other developers out there who are willing to step up to the plate. I hereby want to thank all the speakers and those who contributed in the discussions for all their efforts. The recordings are still there and I do hope many folks were able to learn something. I know I most certainly did.

Having a job closer to home and also being able to work from home at least once a week ensures that I’m able to spend more time with my family. I’m probably most thankful for that. Working out has been a lot of fun this year as well. I was able to drastically improve myself by running longer distances and also running a lot faster. I’m planning to participate in even more street runs during the next year. I’m looking forward to sustainably improve even further without overloading my body. This is definitely one of the biggest challenges for the upcoming year. 

All that’s left for me here is to wish you all the best for the new year!

Until next year. 

Saturday, December 24, 2011

Taking Toddler Steps with Node.js – Express

< The list of previous installments can be found here. >

There are several frameworks out there for building web applications with Node.js, one being more successful than the other. Express is probably the most popular and well known web development framework for Node.js. It’s heavily inspired by Sinatra and built on top of connect, which provides a middleware layer in order to easily add several capabilities and therefore extend your web application. As with most Node.js libraries, Express can be easily installed using npm.

npm install express

The following code snippet shows the most basic HTTP server example using Express:

var express = require('express');
var application = express.createServer();

application.get('/', function(request, response) {
    response.send('Hello Express!!');
});

application.listen(2455);

Notice that this doesn’t differ that much from most Node.js “Hello World” examples out there. So if we point our browser to localhost:2455, then the expected text message appears on the page. Now let’s add some middleware into the mix.

Suppose we want to serve some static content like HTML, CSS and/or JavaScript files. We can simply accomplish that by adding the following line of code.

application.use(express.static(__dirname + '/public'));

Now we simply have to add a new folder named “public” to the root folder of our application. In this folder we add an HTML file named “index.html” with the following content:

<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <h1>Hello Express!!</h1>
    </body>
</html>

Now we have to point our browser to localhost:2455/index.html and our static HTML file is served by Express. That’s how easy we can add capabilities to our web application. Express provides you with several built-in middleware like the one we just used in the last example, but there are also several other open-source middleware in the npm repository to choose from.

Middleware is usually added in a callback function that we provide with the configure method of the application object.

application.configure(function() {
    application.use(express.static(__dirname + '/public'));    
});

Express also provides the ability to configure middleware targeted for specific environments like development, staging, production, etc. … .

application.configure(function() {
    // Shared configuration
    application.use(express.bodyParser());
});

application.configure('development', function() {
    console.log('Configuring middleware for the development environment.');
    application.use(express.static(__dirname + '/public_on_development'));    
});

application.configure('staging', function() {
    console.log('Configuring middleware for the staging environment.');
    application.use(express.static(__dirname + '/public_on_staging'));    
});

application.configure('production', function() {
    console.log('Configuring middleware for the production environment.');
    application.use(express.static(__dirname + '/public'));    
});

Note that we can still provide a separate configuration function for shared configurations between different environments. When we start our web application in the staging environment, we just have to provide the NODE_ENV environment variable.

NODE_ENV=staging nodemon app.js

Now only the global configure function and the one for the staging environment are called.

Express also provides an executable for generating boilerplate code and setting up a basic web application. This is probably the quickest way to get up and running with Express.

node_modules/express/bin$ ./express –h

Usage: express [options] [path]

Options:
  -s, –sessions                  add session support
  -t, --template <engine>  add template <engine> support (jade|ejs). default=jade
  -c, --css <engine>          add stylesheet <engine> support (stylus). default=plain css
  -v, –version                    output framework version
  -h, –help                        output help information

So when I run the express executable with the default options, I get the following output:

./express /home/my_user/my_sample_app

create : /home/my_user/my_sample_app
create : /home/my_user/my_sample_app/package.json
create : /home/my_user/my_sample_app/app.js
create : /home/my_user/my_sample_app/public
create : /home/my_user/my_sample_app/views
create : /home/my_user/my_sample_app/views/layout.jade
create : /home/my_user/my_sample_app/views/index.jade
create : /home/my_user/my_sample_app/routes
create : /home/my_user/my_sample_app/routes/index.js
create : /home/my_user/my_sample_app/public/javascripts
create : /home/my_user/my_sample_app/public/images
create : /home/my_user/my_sample_app/public/stylesheets
create : /home/my_user/my_sample_app/public/stylesheets/style.css

don’t forget to install dependencies:
$ cd /home/my_user/my_sample_app && npm install

A package.json file is created for dependent modules, along with a public folder for JavaScript files and CSS stylesheets and even separate folders for views and routes. This is how the generated app.js file looks like:  

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

app.get('/', routes.index);

app.listen(3000);
console.log("Express server listening on port %d in %s mode", 
       app.address().port, 
       app.settings.env);

As you can see, it’s very easy to get started with Express and adding more capabilities to your web application as you go along. Make sure to watch this short screencast in order to get up and running in no time.

I’m planning to put out a couple more blog posts on Express and some very useful middleware that you can use for your applications. So stay tuned.

Until next time.

Friday, December 16, 2011

Taking Baby Steps with Node.js – Linking Local Packages with npm

< The list of previous installments can be found here. >

I just wanted to share a very neat feature of npm that makes life quite a lot easier when developing libraries for Node.js. Suppose that we’re building our very own ORM library for Node.js (we all build an ORM at some point in our career, right?). In order to have our dog food and eat it too, we want to start using our ORM library in an application as soon as possible. As with all other modules, we want to use npm in order to add it as a dependency of our application. But we also don’t want to publicly publish our half-baked ORM package to the npm repository either. This is where creating an npm link saves the day.

In the local folder of our library we have to create a link by issuing the following command:

~/kick-ass-orm$  npm link

After that we can add this package to the node-modules folder of our application by executing the following command:

~/facebook-killer$ npm link kick-ass-orm

There you have it. Notice that a new folder with the name of the package is added to the node_modules folder of the application. This is simply a symlink to the package folder of our ORM library. This means that when we make changes to this library, those changes are also exposed to our application as well.

As soon as we feel comfortable enough about our ORM library, we can make it publicly available in the npm repository. We can then simply remove the link from our application by issuing the following command:

~/facebook-killer$ npm unlink kick-ass-orm

At this point we add our freshly published package to the package.json file of our application. We can also remove the link from our local package folder by executing the following command:

~/kick-ass-orm$ npm unlink

This particular feature has been very useful to me over the last couple of weeks.

npm – is there anything it can’t do?

Until next time.

Tuesday, October 18, 2011

Taking Baby Steps with Node.js – BDD Style Unit Tests with Jasmine and CoffeeScript

< The list of previous installments can be found here. >

In a previous blog post, I already wrote about BDD style unit tests for testing Node.js modules using Jasmine. I really like the conciseness, simplicity and readability of specification style unit tests using Jasmine. But when we pour CoffeeScript into the mix, then the syntax for BDD style unit tests really starts to get interesting.

Here’s a simple example of a Jasmine test suite written in CoffeeScript:

{ BurglarAlarm, BurglarAlarmState } = require('burglaralarm')
ControlRoom = require('controlroom')
should = require('should')
sinon = require('sinon')

describe 'An armed burglar alarm', ->
    _sut = null

    beforeEach ->
        _sut = new BurglarAlarm()
        _sut.arm()

    describe 'When a break in occurs', ->
        beforeEach ->
            _sut.breakIn()

        it 'should indicate that there is a burglary', ->
            _sut.state().should.equal(BurglarAlarmState.alarm)

        it 'should trigger the siren', ->
            _sut.siren().isRinging().should.be.ok
    
    describe 'When there is being tampered', ->
        _mockedControlRoom = null

        beforeEach ->
            _mockedControlRoom = sinon.mock(ControlRoom.getInstance())
            _mockedControlRoom.expects('notifyTamperAlarm').once()
            
            _sut.tamper()
            
        afterEach ->
            _mockedControlRoom.restore()

        it 'should indicate that there is a tamper alarm', ->
            _sut.state().should.equal(BurglarAlarmState.tamper)

        it 'should notify the control room', ->
            _mockedControlRoom.verify()

 

Personally, I really like this syntax. Notice the destructuring assignment on the first line. This is a small trick we can use when a particular module exports multiple types. We also used a mocking library called Sinon.js which is a very powerful library for test spies, stubs and mocks for JavaScript.

Here’s the code for the BurglarAlarm, ControlRoom and Siren modules. Note that this example code is also written using CoffeeScript, but this can be plain old JavaScript as well if you want.

##############################################
# BurglarAlarm module
##############################################
BurglarAlarmState = 
    normal: 0
    armed: 1
    alarm: 2
    tamper: 3

exports.BurglarAlarmState = BurglarAlarmState

class exports.BurglarAlarm
    _siren = null
    _state = BurglarAlarmState.normal
    
    constructor: ->
        _siren = new Siren()    
        
    siren: -> _siren
    state: -> _state

    arm: -> _state = BurglarAlarmState.armed

    breakIn: -> 
        _state = BurglarAlarmState.alarm
        _siren.makeSomeNoise()    

    tamper: ->
        _state = BurglarAlarmState.tamper
        ControlRoom.getInstance().notifyTamperAlarm()

##############################################
# ControlRoom module
##############################################
class ControlRoom
    notifyTamperAlarm: ->
        console.log('Tamper alarm noticed in the control room ...')

instance = null

module.exports = {
    getInstance: ->
        unless instance?
            instance = new ControlRoom()
        instance
}

##############################################
# Siren module
##############################################
module.exports = class Siren
    ringing = false

    isRinging: -> ringing
    makeSomeNoise: -> ringing = true

 

There you go. Until next time.

Saturday, October 15, 2011

The Cathedral and the Bazaar

A couple of weeks ago, I ran into this website from Eric S. Raymond, the author of the book The Cathedral and the Bazaar. There’s a recording of a great presentation that anyone involved with software development, and especially open-source, should listen to. I highly recommended that you download this recording and at the very least listen to it twice! You can also read the book online.

Enjoy!

Friday, September 23, 2011

Presenting “Taking Baby Steps with Node.js” at Agile.NET 2011 Europe

In a couple of weeks, I’ll be doing an introductory presentation on Node.js at the Agile.NET 2011 conference. While having a look at the other sessions and speakers, I’m quite honored to be able to join these smart bunch of craftsmen. In fact, I’m still amazed that the organizers accepted my proposal. But hey, they’ll probably let me do my talk somewhere in the basement anyway :-).

You probably figured out by now that you can’t afford to miss these two days of high quality learning, especially if you live in the European part of the world. If you live in Belgium or the Netherlands, you simply don’t have any valid excuse for not attending.

If you haven’t registered yet, be sure to do this in the upcoming week in order to get an early-bird discount. And in addition, I can even hook you up with an additional 50 Euro discount. Just drop me a line.

Hope to see you there. 

Monday, September 12, 2011

My First Day at iChoosr

Today was my very first day at iChoosr, a small internet startup that focuses on Vendor Relationship Management. I’ll be working there as a web developer in a small team of very bright people. Working for a small startup is a totally new experience for me. So I’m very excited about what the future will bring.  

Pretty sure there’s lots of learning ahead of me Smile

Friday, September 09, 2011

An Observation about TDD

To me, developers that are not applying TDD practices during their day-to-day job always seem more in a hurry than developers that do apply red-green-refactor. In their hurry, they're the first to cut corners and start making messes while they rush to their goal. A while ago it dawned to me why that is. They subconsciously want to get feedback as soon as possible about the code they're writing. They cut corners and generally mess up their code in order to prevent spending those extra hours and days to keep things clean. Constantly refactoring and cleaning up their code is restraining them from having the feedback they so desperately want.

Humans are in fact feedback junkies. We constantly want to know how we're doing what we're doing. I actually wrote a blog post about this a couple of years ago.

Since I adopted TDD as a discipline, I tend to feel less pressured which results in me taking the time to continuously refactor the code I'm working on, trying to keep everything clean. Why? Because I known that the code I wrote a minute ago works. The tests I write constantly give me a shot of feedback so that I'm constantly hooked. 

Just an observation ...

Tuesday, September 06, 2011

Book Review: The Clean Coder

The Clean Coder: A Code of Conduct for Professional Programmers

Earlier this week I finished reading Uncle Bob’s latest book The Clean Coder. Robert C. Martin is a great writer and I very much enjoyed reading his previous books. His latest work is no exception and I found it to be yet again a fascinating read.

This book is all about professionalism. This is something that is very much needed in the field of software development. It describes how a professional software craftsman behaves, how he deals with tight schedules, irrational decisions made by managers (for those rare occasions that this happens), conflicts and so forth. The preface of the book takes you right by the throat, talking about the Challenger disaster. This has been applied to the field of software engineering many times already (check out this blog post from Gustavo Duarte which is one of my all-time favorites), but still, it definitely never wears off.

The book is filled with stories and anecdotes from the rich career of the author and the lessons he learned during these 40+ years in the IT industry. Some of the ideas in there are definitely challenging (like staying out of the zone and building up focus instead), but nonetheless they put a very  interesting perspective on things.

Don’t let yourself get carried away by some of the hard statements but try to focus on the underlying ideas and try to think back on some of the good and bad situations that you ran into during your own career. Trying to reflect on those moments and considering how we could act more professionally lies at the heart of improving ourselves. I definitely learned a lot while reading this book and I encourage you to pick up a copy as soon as possible and take some time to read it.

Two thumbs up!

Tuesday, August 16, 2011

Book Reviews: CoffeeScript and JavaScript Web Applications

While catching up on my reading backlog, I particularly enjoyed reading two new books I bought recently which I’m going to briefly discuss in this blog post.

1. CoffeeScript - Accelerated JavaScript Development

Cover Image For CoffeeScript

CoffeeScript – Accelerated JavaScript Development, written by Trevor Burnham, gets you up and running with CoffeeScript in no time. This book was recently released by the excellent Pragmatic Programmers which only increased my expectations.  And I must admit that Trevor did a tremendous job explaining the ins and outs of this fairly new programming language. With only a good 120 pages, it’s a very quick read so one is able to start coding away as soon as possible.

The book contains six chapters. The first four chapters basically cover the different language features of CoffeeScript. The last two chapters explain how to use CoffeeScript both on the client-side along with jQuery and the server-side with Node.js. At the end of each chapter there’s an example application (5x5 solitaire) that gets refactored throughout the book as more language features are covered. Every chapter also provides some exercises where you can put your teeth into.

Now, I have to warn you that in order to get the most out of this book, you need to have some decent knowledge of JavaScript. Some of this stuff isn’t trivial and being able to imagine how the underlying JavaScript would look like is almost required.

I highly recommend this book if you want to learn this great little programming language.

2. JavaScript Web Applications

Book cover of JavaScript Web Applications

By the time of this writing, JavaScript Web Applications by Alex MacCaw hasn’t officially been released yet. It’s still in the early release phase which means that there are still a good number of typos in there. That aside, this book contains some rock solid content on how to build client-side JavaScript applications.

This book isn’t about server-side applications with the occasional piece of JavaScript code used in only a couple of web pages. As it’s name implies, this book is all about building MVC applications for the browser using JavaScript.

After the obligatory introductory chapter, chapter 2 up to chapter 6 discuss each part of the MVC pattern and events. The author thoroughly explains each part of this design pattern while implementing his own client-side MVC library. Lots and lots of code here.

Chapter 7 provides a clear explanation on dependency management in JavaScript and how to use module loaders to mitigate this problem. Chapter 8 and 9 cover some of the API’s that come with the upcoming HTML 5 standard, particularly on how to deal with files using JavaScript as well as WebSockets. Chapter 10 deals with testing and debugging. But chapter 11 is definitely my favorite chapter of the book where the author shows a good number of techniques on deploying a JavaScript web application and how to deal with performance. This chapter alone was a real eye opener. Finally, the last three chapters provide an in-depth introduction to three of the most popular open-source client-side JavaScript libraries out there, namely Spine.js, Backbone.js and JavaScriptMVC.

Again I have to warn you that this book is definitely not for JavaScript beginners or the faint of heart. There were times that it even got me scratching my head from time to time. There’s some really neat JavaScript stuff in there, so I highly recommend that you pick up this book some time on your JavaScript learning path.

Happy reading an until next time.

Thursday, August 11, 2011

Dynamic in C# is Broken

Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from C# in Depth that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant surprise. Let’s look at some code.

public interface IPresenter
{
    void Start(dynamic startupData);
}

public interface ISpecificPresenter : IPresenter
{}

public class SpecificPresenter : ISpecificPresenter
{
    public void Start(dynamic startupData)
    {
        // ...
    }
}

Here we have an interface called IPresenter with a single method on it named Start. Notice that the Start method has a single parameter which is defined as dynamic. We also have another interface called ISpecificPresenter that inherits from IPresenter. Finally we have a concrete class that implements the ISpecificPresenter interface. So far, so good.

Next we have a class called Activator that we use to kick-off a particular presenter.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

The Activator class has a generic Start method with a parameter named startupData that is also dynamic. Here we simply get an instance of a requested presenter from StructureMap and call its Start method. This is how to call the Start method of the Activator class :

var activator = new Activator();
activator.Start<ISpecificPresenter>(new{});

When we run this code, we get the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ISpecificPresenter' does not contain a definition for 'Start'.

This had me stumped for a while until I added a cast from ISpecificPresenter to IPresenter in the Start method of the Activator class.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = (IPresenter)ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

Now everything works as expected. But I’m not entirely sure why this isn’t behaving as I expected. I guess it has something to do with the fact that the Start method is defined on the IPresenter interface and not on the ISpecificPresenter interface.

image

Although I very much like the flexibility that dynamic objects bring to the C# language, I’m also starting to think that it might not be such a good idea to bring dynamic concepts to a statically typed language. Running into these kind of issues and limitations reinforces this growing opinion.

I would much appreciate it if anyone could enlighten me with a good explanation.

Until next time.

Tuesday, August 09, 2011

Exploring CoffeeScript Part 6 - Show Me the Goodies !

For the final blog post in this series, we’re going to go over a couple of cool little nuggets that one can use to write some elegant CoffeeScript code.

Also check out the previous installments:

  1. And Then There Was Coffee
  2. Variables and Functions
  3. More on Functions
  4. Objects and Classes
  5. Ranges, Loops and Comprehensions

Destructuring Assignments

Destructuring assignments are a great syntactic enhancement for those cases where we want to extract (deeply) nested property values from arrays or objects and store these values into variables.

First let’s have a look at a simple code example written in plain JavaScript where we simply assign some property values of an object to a couple of variables.

var podcast = {
    title: 'Astronomy Cast',
    description: 'A fact-based journey through the galaxy.',
    details: {
        homepage: 'http://www.astronomycast.com',
        rss: "http://www.astronomycast.com/feed/",
        atom: "http://www.astronomycast.com/feed/atom/"    
    }
};

var title = podcast.title;
var description = podcast.description;
var homepage = podcast.details.homepage;

console.log(title);
console.log(description);
console.log(homepage);

Using destructuring assignments in CoffeeScript, we can assign the property values of the object to the variables using a single line of code.

podcast =
    title: 'Astronomy Cast'
    description: 'A fact-based journey through the galaxy.'
    details:
        homepage: 'http://www.astronomycast.com'
        rss: 'http://www.astronomycast.com/feed/'
        atom: 'http://www.astronomycast.com/feed/atom/'

{title, description, details: { homepage } } = podcast

console.log title
console.log description
console.log homepage

Besides objects, destructuring assignments also works for arrays as well.

favoritePodcasts = ['Astronomy Cast', 'Hardcore History', 
                    'Talking Shop Down Under', 'The Changelog', 'Pluralcast'];
[favorite01, favorite02, favorite03, favorite04, favorite05] = favoritePodcasts

console.log favorite01
console.log favorite02
console.log favorite03
console.log favorite04
console.log favorite05

And of course, this can also be used when combine objects with arrays and vice versa.

customer =
    firstName: 'Chuck'
    lastName: 'Norris'
    orders: [
        { 
            Id: 1 
            Item: 'Knuckle Duster'
        },
        { 
            Id: 2
            Item: 'Shuriken' 
        }
    ]

{orders: [ {Item: item1}, {Item: item2}]} = customer

console.log item1
console.log item2

This small little language nugget has definitely come in handy quite more often than I first anticipated. So do keep the availability of destructuring assignments in the back of your head while developing CoffeeScript code.

String Interpolation

The syntax for string interpolation is heavily inspired on the Ruby syntax. Let’s have a look.

podcast = 
    title: 'Astronomy Cast'
    download: (episode) ->
        console.log "Downloading #{episode} of #{@title}."

podcast.download 'the first episode'

In this example we fill in the values of the episode parameter and the title property into the string that we send to the console.log method. Unfortunately string interpolation only works for double quoted strings. I personally prefer single-quoted strings when I’m writing CoffeeScript code. But I gladly make an exception when I want to use string interpolation.

Strict Equality

In JavaScript, we have the == and the === operator. Both equality operators behave the same way only the first performs type coercion while the latter enforces type equality. It's a common best practice in JavaScript to always use the strict equality operator and explicitly perform type casts if needed. CoffeeScript on the other hand only has only one equality operator which always translates to JavaScript's strict equality operator behind the scenes.

So the following equality comparison written in CoffeeScript translates to the JavaScript code shown bellow:

# CoffeeScript
x = 'str'
y = 12
console.log x == y        # Outputs 'false'


// JavaScript
var x, y;
x = 'str';
y = 12;
console.log(x === y);

As I already mentioned in one of the previous blog posts, CoffeeScript emits JavaScript that follows best practices and complies to JSLint without warnings. Always using the === operator is part of being compliant.

Conditionals

CoffeeScript adds some nicely readable syntactic sugar to be used with conditionals using keywords like unless, is, isnt, and and or. Let’s look at an example.

cobol = vb = false
cool = true

unless cobol is cool
    console.log 'CoffeeScript is awesome!'

if vb isnt cool
    console.log 'CoffeeScript is awesome!'

if cobol isnt cool and vb isnt cool
    console.log 'CoffeeScript is awesome!'

I really like how these keywords enable us to write fluently readable conditional statements in CoffeeScript.

The Existential Operator

The existential operator in CoffeeScript, expressed using the ? symbol, returns true except when a particular variable is null or undefined. Let’s look at some code.

someVariable = null
someOtherVariable = 12

console.log someVariable ? someOtherVariable        # Outputs 12

unless someVariable?
    console.log 'someVariable is null'

But the existential operator can also be used to check for null or undefined before accessing a property or the result of a function. This is also called a soak which is the accessor variant of the existential operator. Again some code to clarify things.

podcast =
    title: 'Astronomy Cast'
    description: 'A fact-based journey through the galaxy.'
    details:
        homepage: 'http://www.astronomycast.com'
        rss: 'http://www.astronomycast.com/feed/'
        atom: 'http://www.astronomycast.com/feed/atom/'

    download: -> null

# Outputs 'http://www.astronomycast.com'
console.log podcast.details.homepage    

# TypeError: Cannot read property 'publishingDate' of undefined            
console.log podcast.moreDetails.publishingDate        

# Outputs undefined
console.log podcast.moreDetails?.publishingDate     

# Also outputs undefined
console.log podcast.download()?.data

When the property in question has a valid value, then the expected result is returned. In case the property does not exist or contains null, then undefined is returned instead of a TypeError being thrown.

So that’s it for now. I hope that you enjoyed reading this blog series on CoffeeScript and perhaps you are now also convinced that using CoffeeScript is a viable and productive alternative for writing JavaScript based applications.

Until next time.

Saturday, August 06, 2011

Moving from E-TextEditor to Sublime Text 2

I’ve been using E-TextEditor for more than a year now for doing all my JavaScript, Node.js and CoffeeScript development. You can think of E-TextEditor as TextMate for the Windows platform. I’ve been pretty happy with it throughout this period as it can be extended pretty easily with a whole slew of bundles that are already available for TextMate. E-TextEditor requires you to install Cygwin which happens automatically during installation. Using the Cygwin command-line gave me enough (re-)exposure to a Linux-like environment in order for me wanting to (re-)learn about this other platform. More on that in later blog posts. Although there haven’t been any new versions of E-TextEditor for quite some time now, the current version enabled me to write JavaScript code in a productive way.

Only recently I found out about another editor called Sublime Text 2 (thanks to Ivan Porto Carrero). I downloaded this text editor in order to give it a try and I must say that I haven’t opened E-TextEditor ever since. This second version of Sublime Text is still in development but it’s pretty stable as I haven’t run into any issues so far. The cool part is that this editor is available for both Windows, Linux and OS X which enabled me to move all my Node.js and CoffeeScript development from Cygwin on Windows to Ubuntu Linux. 

CoffeeScript isn’t supported out-of-the-box (yet), so I installed the CoffeeScript  TextMate bundle written by Jeremy Ashkenas (yes, the same one from the CoffeeScript and Backbone.js fame). Also check out this page on the CoffeeScript wiki for more information on how to bring some CoffeeScript happiness to your own favorite text editor.

Setting up this TextMate bundle for use with Sublime Text 2 was actually pretty easy. Just navigate to /home/<my_user_name>/.config/sublime-text-2/Packages in a terminal (or the corresponding file path on Windows) and clone the source of the CoffeeScript TextMate bundle using git:

git clone git://github.com/jashkenas/coffee-script-tmbundle CoffeeScript

Next close all the .coffee files and restart Sublime Text 2. Now we have some nice syntax highlighting and some useful code snippets at our disposal. 

image

It's also possible to hook into the build system of Sublime Text 2. You just need to create a new file named CoffeeScript.sublime-build at the following location:

/home/<my_user_name>/.config/sublime-text-2/Packages/User 

You can add the following to this new file for compiling CoffeeScript

{
     "cmd": ["coffee", "-c", "$file"],
     "selector" : "source.coffee",
     "path" : "/usr/local/bin"
}
or the following for executing/running CoffeeScript code.
{
     "cmd": ["coffee", "$file"],
     "selector" : "source.coffee",
     "path" : "/usr/local/bin"
}

Now when you hit F7, this fresh build command is executed when a CoffeeScript source file is showing in the active tab. It’s also possible to change the build short-key to your own taste through the Preferences menu. 

Unfortunately, there’s only one build command as I would love to create a separate command for compiling and running CoffeeScript code (or perhaps I missed this feature during the excitement Winking smile).

Some more usage is definitely needed for me to learn more about this excellent text editor, but currently I’m pretty happy with it. I also need to find out how well JavaScript is supported and perhaps see how far one can go when doing some C# development using Mono. I expect that there are a good number of productive features in there for me to discover.

I encourage you have a decent look at this excellent tool.

Until next time.