How to loop good

…or “Short rant on why C-style for-loops are almost always unnecessary “…

If you’ve been with C# for the last couple of years, your coding style has probably evolved in a more functional direction since the introduction of C# 3/.NET 3.5 with all its LINQ and lambda goodness.

In my own code, I have almost completely dismissed the old C-style for-loop in favor of .Select, .Where etc., making the code way more readable and maintainable.

The readability and maintainability is improved because long sequences for for/ foreach and collection-juggling can now be replaced by oneliners of selection, mapping, and projection.

One place, however, where I often see the for-loop used, is when people need to build sequences of repeated objects, or where some variable is incremented for each iteration.

Now, here is a message to those developers: Please realize that what you actually want to do is to repeat an object or map a sequence of numbers to a sequence of objects.

Having realized that, please just implement it like that:

Same thing goes for sequences of elements where something is incremented:

There’s just too many for-loops in the world!

Not the same thing, but still somehow related to that, is when people need to collect stuff from multiple properties and ultimately subject each value to the same treatment – please just implement it like that:

</rant>

How to avoid (unnecessarily) touching the container

…or “How to resolve stuff all over the place” – two appropriate titles for a blog post that shows the solution to a problem you will eventually run into when using an IoC container… if not in your first application, then maybe in the next…

What’s the problem?

Not all applications lend themselves equally well to leveraging an IoC container for resolving stuff. Generally, applications that follow some kind of request-response pattern are easy to adapt to use the container to build objects that handle requests: Just resolve some kind of handler that handles each request.

E.g.: It is trivial to make Castle Windsor resolve/release controllers in an ASP.NET MVC application by implementing a CastleWindsorControllerFactory.

There are applications however, that do not follow this kind of pattern – or at least not as clearly. Take for instance a typical Windows Forms desktop application that looks like this:

An attempt to use the container could look like this:

But then one problem remains: How can we make the Windows Forms application use our beloved Windsor Container without resolving the entire world at this point?

E.g. if MainForm at some point needs to show a SubForm, then how do we do that without doing a new SubForm() inside of MainForm, thus tying MainForm directly to the concrete SubForm? (and worse: ruining our ability to unit test MainForm…?)

Let’s try using a service locator

In order to avoid new’ing up SubForm, we could use a service locator to provide the form to us. Consider this button handler:

That solves the problem, right? Wrong! I mean, now SubForm can have dependencies injected and stuff, but MainForm is tied to a class called ServiceLocator with a static generic method that creates stuff.

That’s pretty hard to unit test, and in the long run this will just prove to be a serious PITA.

How to fix the problem

If we wanted to fix the problem with MainForm and SubForm, we could do it by passing a ISubFormFactory to MainForm like so:

thus allowing MainForm to instantiate SubForms at will without depending directly on the container. Now on to implement ISubFormFactory:

Now, why is that implementation uncool? There are several reasons, and two of them are: 1) I’m tying myself to a Windsor container somewhere in a static variable in my app, and 2) The implementation is stupid and boilerplate – I need to write one of these every time I need to show a new form… Uncool!

Enter TypedFactoryFacility

Windsor comes with a bunch of facilities in the box, and one of them fits this gap nicely: <a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx">TypedFactoryFacility</a>.

If TypedFactoryFacility had a tagline it would be either “The missing link!” or “Gimme another chance!” or something like that.

Put shortly, TypedFactoryFacility gives the container the ability to dynamically implement the ISubFormFactory interface from above, thus allowing my code to pull stuff from the container without even knowing it! \o/

In order to do that, I need to start out by registering the facility;

and then I need to register my factory service like so:

Now the container will delegate the call to CreateSubForm() to container.Resolve<SubForm>(), based on the return type of the factory method – nifty!

When working with Windsor, it is very important that everything that has a transient lifestyle gets properly released! – the facility has this capability as well, just implement a method with the following signature on the factory: void Release(SubForm subForm).

Now our MainForm’s event handler can look like this:

allowing Windsor to properly take care of decommission concerns, thus properly disposing IDisposables and more.

I hope this post gave an understandable introduction to TypedFactoryFacility. To help some more, I have created a simple Windows Forms application on GitHub that shows how a simple Windows Forms application can implement a simple MVC pattern using Castle Windsor and TypedFactoryFacility.

Comments, questions and suggestions are appreciated 🙂

What is that module thing again?

This is the fourth post in a small series on Node.js. In this post, I will take a look at how the Node.js module mechanism works.

In my previous posts on Node.js, I nonchalantly went ahead and require(...)d something called http – but what was that? And what happened when I did that?

Well, require is one of the few globals when running a Node program, and it is used to import a module. The parameter is a string, which Node uses to look for a file to load.

The simplest usage refers directly to a file relative to the path of the currently running program. E.g., if I have a module residing in a file called importantBizLogic.js in the lib folder beneath my program’s directory, I can include its exports (which I’ll get back to in a moment :)) like so:

If I omit the ./, Node will go look for importantBizLogic in each directory in the require.paths array, which is a list of default paths to search for modules.

Let’s see what it contains… Go to a terminal and enter the Node shell:

Great – so that’ s where my global modules reside. Now, what was that export thing again?

Well, that’s related to how importantBizLogic.js is structured… in order to control how the import works, a module must explicitly export stuff – and that can be done like so:

– allowing this module to be imported and used like so:

Nifty!

Apparently – and I am almost embarrassed that I did not know that – there is a thing called CommonJS, which is an initiative that strives to create a JavaScript standards library – and the require stuff I’ve described here is actually just Node implementating the CommonJS Modules specification. Pretty sweet, actually!

Up and running with Express

This is the third post in a small series on Node.js. In this post, I will take a look at how to get up and running with Express.

Let’s get Express installed – first, let’s install NPM – a package manager for Node:

That was easy. Now, Express can installed like this:

Too easy!

Now, let’s create a simple app like we did the last time:

Punch in the following few lines:

and run the app from the terminal like so:

and navigate to http://localhost:3000 – on my machine it looked like this:
Hello Express

That was easy. See how the API pretty much resembles Node’s builtin HTTP server, except it adds routes into the mix!

Now, in order to build a web site we need some kind of view engine to help generate some HTML for us. I have used Haml a couple of years ago, and I really liked it… and luckily, some nice people have made Haml available to Node apps, so let’s try installing that:

Now we configure Express by punching in the following stuff in the app:

As you can see, I tell Express to use Haml as the default view engine. Moreover, I configure Express to serve static content from the /public folder in my app dir, and then I install the bodyDecoder middleware which will parse incoming posts and make posted values available in req.body.

Now, let’s alter our action to render a view:

and now create two files, layout.haml and index.haml in the /views folder. Mine look like this – /views/layout.haml:

and /views/index.haml:

Now, let’s go to the terminal and node app.js and navigate to http://localhost:3000 – on my computer it looks like this:
Hello Express + Haml

As you can see, view models can be handed to the view via the locals object.

This was some basic web app stuff – only thing missing is some way to persist data, so next time I will take a look at how to get my Mongo on…

Getting started with Node.js

This is the second post in a small series on Node.js. In this post, I will take a look at how to get started and run the ubiquitous “Hello world” sample.

First, create a directory somewhere and Git clone Node… I did it like this:

Then, build and install Node like this:

If you get permission errors during the last step, you might need to do a

to grant yourself ownership of everything beneath /usr/local. Note however, that this should probably only be done if the machine is your own personal machine.

Now, try typing node -v in the terminal… I got this:

Now, let’s finish this post by creating a Node app like so (using TextMate or whatever you prefer):

Punch in the following few lines:

and go the terminal again and type

which yields

Now, when I navigate to http://localhost:8124 I get this:

Node.js HTTP Hello World

Nifty, huh?

In the next post, I will see if I can get up and running with Express – a simple but powerful Sinatra-like web framework for Node.

I want to learn Node.js

Preface

More than three years ago, I watched a couple of videos with Douglas Crockford that changed my view on JavaScript completely!

I must admit that I too used to consider JavaScript a toy language, somehow inferior to “real programming languages” like Java and C#.

This view was of course induced by the sheer amount of JavaScript crap code available to copy/paste from the web, almost always operating on an equally crappy non-standards compliant DOM implementation in some crappy browser – but after watching those videos I actually began to understand that JavaScript was a pretty cool and powerful language.

Some time after, Crockford released JavaScript: The Good Parts which I immediately read, and at that time I remember saying to one of my colleagues: “I think it would be cool to build large systems in JavaScript”.

At that time, stuff like Rhino was around, but I had never heard of anyone actually using it, and executing JavaScript on the JVM by compiling JavaScript into Java into bytecode didn’t sound sexy at all to me.

Today

Recently, however, I have somehow come across Node.js at different occasions, and I have really been meaning to check it out. If you don’t know what Node is about, I can quote the homepage: Node is “Evented I/O for V8 JavaScript.”

That’s right! Let’s break that down:

  • Evented: There’s only one thread executing in a Node process, high throughput is achieved by doing asyncronous I/O, queueing callbacks to be executed upon completion.
  • I/O: Not usually what JavaScript is used for, but this covers the fact that Node has APIs that treat the file system and TCP and HTTP as first class citizens.
  • V8: The JavaScript is executed by the V8 JavaScript Engine that Google in Aarhus built for Chrome.

As an example, there’s the ubiquitous code sample that you’ll see everywhere – opening a HTTP server in Node:

As you can see, Node has a nice and thin API for working with HTTP, and as I envy Rubyists of having Rack and Sinatra, and as I am interested in how web frameworks work in general, this code sample has continued to spark my interest.

Therefore, in order to push myself through learning more about it, I have decided to see if I can write a couple of blog posts on Node.js. I will try to cover the necessary topics to develop a simple web app, and I expect to come across more or less of the following:

  • Acquiring Node.js and running a “Hello world” script. Can’t do anything without having done this.
  • Basic Node stuff, like how to structure code into files/modules/whatever and whatnot.
  • Bringing in external, possibly native libraries.
  • Building a web app, possibly with Express – a simple web framework for Node.
  • Persisting some data, probably using node-mongodb – a MongoDB driver for Node.
  • Unit testing my app – probably with the built-in assert API.
  • Hosting my app – probably with Nginx as a router and load balancer.

Wow! – that was a lot of words and almost no code… I promise that my next posts on Node will have more code in them.