Sergio and the sigil

JavaScript: Not your father's inheritance model - Part 2

Posted by Sergio on 2009-06-12
This post is part of a series called JavaScript Demystified.

This particular chapter is further divided in two parts. Read Part 1.

Build your own hierarchy

Let's pretend we are building some scripts that deal with musical instruments. We could define our own Guitar class type like this:

//The constructor
function Guitar(brand, model) {
    this.brand = brand;
    this.model = model;
    this.strings = ['E', 'A', 'D', 'G', 'B', 'e'];
}

//Instance methods
Guitar.prototype = {
    play: function (chord) {
        alert('Playing ' + chord); 
    },
    toString: function () {
        return '(Guitar: ' + 
            this.brand + ' ' +
            this.model + ')';
    }
};

var guitar1 = new Guitar('Gibson', 'Les Paul');

What may not be apparent by just looking at the code for the first time is that guitar1's Prototype will be Guitar.prototype, which means that guitar1 inherits from Guitar.prototype. Also guitar1.constructor === Guitar.

When the last line in the above example is executed, the JavaScript runtime will take care of initializing a new object that has Guitar.prototype as its Prototype and makes its constructor property point to the Guitar function.

But what if we want to create a different type of guitars and still reuse the existing Guitar type. We could do this:

function BassGuitar(brand, model) {
    //call the constructor of our base type
    Guitar.apply(this, [brand, model] );
    //change or add anything we wish
    this.strings = ['E', 'A', 'D', 'G'];
}

//Copy the Prototype of our base type
BassGuitar.prototype = Object.create(Guitar.prototype);

//Override whatever we want:
BassGuitar.prototype.toString = function () {
    return '(BassGuitar: ' + 
        this.brand + ' ' +
        this.model + ')';
};

var bass1 = new BassGuitar('Peavey', 'Cirrus');
bass1.toString(); //=> '(BassGuitar: Peavey Cirrus)'
alert(bass1.strings); //=> [ 'E', 'A', 'D', 'G' ]

But there's a problem with the above code. There isn't a method Object.create(). Yeah, that's one of the design omissions in JavaScript. Any prototype-based language needs an easy way to let use create objects from other objects.

Thankfully JavaScript is also dynamically typed, so we can add that function ourselves. Here I'm borrowing from Douglas Crockford.

//add this to the very beginning of your scripts
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

I'll leave the interpretation of the above function as an exercise to the reader. Once you understand what it is doing you will have mastered prototypes and constructors.

Handy Prototype tricks

Knowing what we know now and once again leveraging JavaScript's dynamism we can fix one of the things that has always annoyed me in JavaScript: the lack of a trim() method on strings.

String.prototype.trim = function () {
    return this.replace( /^\s*(\S*(\s+\S+)*)\s*$/, "$1"); 
}; 
var text = ' some user-entered value   ';
alert( text.trim() ); // => 'some user-entered value'

How about an easy way to pad numbers with zeroes?

Number.prototype.padLeft = function (width) {
    var text = this.toString();
    for(; text.length < width; ){
        text = '0' + text;
    }
    return text;
};

var num = 1234;
alert(num.padLeft(6)); // => 001234

Why do I need to know all this stuff?

Well, you don't. But why even bother writing JavaScript code if you're not willing to learn how it works?

As we have been seeing during this series, JavaScript bears only some syntax similarities with C# or Java. Underneath the surface it has been designed very differently. The web is riddled with attempts to mimic class-based inheritance in JavaScript only because programmers don't want to learn and leverage prototype-based logic.

My humble advice is that you will feel happier and smarter if you chose to learn how to use the language as it was intended.

So you've been hearing about this Git thing

Posted by Sergio on 2009-06-02

The ALT.NET universe in Chicago gets together again on June 10th, this time to learn and talk about Git, the SCM you're probably tired of hearing people jabbering about and still have not taken the time to look at.

The presenter will be myself and I hope to explain how Git works and how it can be a good alternative even for non open source projects.

Git Without Puns

This month we will take a look at Git, a distributed version control system that has been gaining a lot of popularity since its introduction.

As with everything that is new and is touted as a replacement for an existing product, it's easy to try and map Git's functionality to Subversion, CVS or TFS for example. To better use Git, we should avoid too much comparison and also try to understand how it was built and how it works under the hood.

Here are the things we will be seeing and discussing in this session.

  • Brief tour of Git on Windows (SSH, PuTTY, Git Bash, GUI)
  • Git is distributed. How does that benefits me?
  • Git's object database.
  • Git's main objects (blobs, trees, commits and tags)
  • Git workflows. Choose or create yours.
  • Working with Git
    • Configuration tips
    • Create a repo
    • Clone a repo
    • Add/Commit changes
    • Reference another repo
    • Update repo (to/from)
    • Branching, merging, rebasing
  • Hosting Git
  • Github, social project forking

The Chicago Code Camp has got you covered

Posted by Sergio on 2009-05-19

As a brief inspection of your RSS reader will quickly tell you, it's Code Camp season. Not to be left out of this party, the developers in the Chicago and Milwaukee areas have a great option this year.

The Chicago Code Camp, which happens on May 30th, is strategically located right between these two cities.

The agenda has been published and it's pretty exciting to see so many interesting and useful topics in a single event.

.NET still dominates the schedule but there's a lot of options for developers of virtually all walks of life. Here's a quick summary (we will have 33 sessions but some cover more than one topic)

  • .NET: 20 sessions
  • Ruby: 6 sessions
  • TDD: 6 sessions
  • JavaScript: 3 sessions
  • Functional Programming: 3 sessions
  • Cloud computing: 3 sessions
  • Python: 2 sessions
  • Java: 2 sessions

The bad part is that we can't be at all the sessions we'd like — there will be 5 or 6 concurrent talks. Here are some sessions that interest me in particular:

Those are only a few of the talks. I'm sure you'll be able to find sessions of your own interest. RSVP below. Hope to see you there.

RSVP

Git, SSH, PuTTY, GitHub, Unfuddle, the kitchen sink

Posted by Sergio on 2009-05-06

After reading a good number of the guides for getting Git/ GitHub/ Unfuddle working correctly in Windows, I finally got it sorted out. I had to use a bunch of things I had not used before so I realized it's probably a good idea to share my findings, hoping to help someone else (and maybe myself again) in the future.

Local git is easier

Getting Git to run locally in Windows is not hard. It gets a little trickier when you want to work with remote repositories. Especially if, like me, you have little or no experience using SSH in Windows.

In this post I'll install and configure the tools that enable Git to work with remote repositories (e.g. post changes to a server), which I think is probably what a lot of people will want to do, even if you're just toying with Git or evaluating it.

You will need SSH for serious Gitting

The way Git will authenticate and communicate with hosted repositories like GitHub or Unfuddle is through an SSH tunnel. That means we will need an SSH client to connect to the server and Git will use that connection to securely transfer the repository data up and down.

In Linux or on the Mac, SSH is a trivial thing. It's just part of the default installation. For whatever reason, Windows does not come with an SSH client, so we need to find ourselves a 3rd party client.

PuTTY, a family of tools

Luckily for us, there's a free and very popular SSH client for Windows, called PuTTY. PuTTY is actually a family of utilities that play together to configure and establish SSH (and Telnet) connections.

From the PuTTY downloads page get the following programs and put somewhere in your hard disk. I like to put these types of things in a c:\tools\bin directory, which is included in my %PATH%.

Create your SSH key pair

The most common way to authenticate your SSH connection with the server is using an RSA key pair. The pair contains a public key and a private key. Typically these keys will be stored in two files — make sure that the private key file is in a directory location that only your user account has rights. I'm gonna keep both files in %USERPROFILE%\SSH (type echo %USERPROFILE% in a command window to see where yours is.)

To create a key pair we will use puttygen.exe. Just click Generate and then Save public key and Save private key. I chose to leave the password blank and trust that my directory security is enough to protect my keys. Let's assume I saved my keys at %USERPROFILE%\SSH\private.ppk and %USERPROFILE%\SSH\public.ppk, respectively.

We're not done with PuTTY yet

Before starting an SSH connection with PuTTY, we need to run Pageant.exe. Pageant is a background process that will handle the authentication requests. We will add our private key(s) in Pageant and it will keep them available for new connections, without the need to retype the password (if you entered one) every single time.

Run Pageant.exe, double click its icon in the notification area, and add your private key file. If you specified a password, it will now prompt you for that.

Phew! We are done with the SSH crap. Now on to Git. Finally.

Git via msysgit

There are a few ways of installing the git client in Windows, including downloading and compiling the source. But guess if I want to go down that route. Instead, let's just press the easy button and use a pre-packaged installer.

msysgit is what you'll want to install. Donwload the latest release from the site. The file name of the full installer, as of this writing, will be named like Git-[version]-preview[yyyymmdd].exe.

Run the installer accepting most of the defaults, with the exception of these two screens below. We want to Run Git from the Windows Command Prompt and Use PLink (PuTTY.)

 

After this we should have a working installation of Git. You should be able to use Git from both the Windows command prompt and from the Git Bash shell.

Register your public key with the remote server

Now we need to tell the server that hosts the remote repository that it should expect and accept SSH connections from our machine. The way we do this is similar in GitHub and Unfuddle. We just need to associate our public key with our account on that site.

For example, in my GitHub account settings there's a section called SSH Public Keys, where we can add all public keys that we own. Don't use the public key straight from your PuTTY public key file, it uses a different format. Instead, open Puttygen again and load the private key. The public key, in the right format, will be shown in the big text box at the top of the window. Copy that entire text and paste in a new key in your GitHub settings, as seen below.

Troubleshooting

After all that you should have all it takes to use Git in Windows. Until I got to this point I came across some problems. Here are some of them.

No supported authentication methods available. I got that error while trying to push changes because I either forgot to run Pageant or to add the right key into it. The full error is below.

C:\myproject>git push origin master
FATAL ERROR: Disconnected: No supported authentication methods available
fatal: The remote end hung up unexpectedly

The server's host key is not cached in the registry. Sometimes when connecting to a remote server for the first time, the PuTYY will output this message after your Git command.

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 1024 [fingerprint here]
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Talk: If you think F# has too limited applicability

Posted by Sergio on 2009-04-30

Next Chicago ALT.NET meeting will bring a practical look at F#, showing that it does not need to be seen as a niche language.

F# Outside the Lab

6:00 pm
Pizza and networking time

6:30 pm

It seems that almost every time we hear about F# being used it is always in a experimental setting or in a niche application. Maybe that's a common trait that F# shares with many other functional programming languages and its roots in the Microsoft Research labs.

Alex Pedenko has been exploring uses for F# for day-to-day programming tasks and he will be sharing his experience with the group in this talk.

Alex will start with a quick introduction to F# but it would work best if you could at least skimmed over some tutorial or video just to get the basic syntax and feel of the language.

Alex has been in software development for about 13 years, starting off on Borland Delphi, then spending about 4 years in Java and finally making the switch to .net around '03

Currently, he is the director of software architecture and chief architect at a healthcare services company. He has used that role as an opportunity to inject some modern ideas into an otherwise lagging industry, moving the company from a classic "giant web-app strapped to an even more giant db", to a distributed, service-oriented environment utilizing RESTful services, and rich-client applications.

He has spent roughly 6 months researching f#, its applicability to business systems, and viability in a commercial environment.

He adds:

I like long walks on the beach... er.. wait, that's for a different site :)

7:45 pm

Time for our monthly open discussion (if the 1st portion doesn't run late). Functional programming, either in a real functional language or in C#, JavaScript, Ruby, etc, which support some of the same constructs, is making inroads on software development. Is it the next big thing or just one more thing in our toolbox?