Sublime Text 2 Strip Whitespace on Save

I’ve become fond of Sublime Text 2. Gasp! Wait, what? You don’t use emacs/vim/butterflies? Anyway, regardless of the editor, I like to keep my whitespace under control. This usually means I add a hook to strip trailing whitespace when saving. The Sublime Text 2 Python API reference looks pretty complete, but there’s little pragmatic documentation. I tinkered with creating my own, found others that had semi decent solutions, but ultimately gave up. After my failed attempts and failed googling, my coworker informed me that Sublime Text has this built right in as a user setting you can set by adding a simple JSON snippet. Awesome.

Make it Happen

Go to SublimeText 2 > Preferences > User Settings (or just hit the Mac Standard cmd + ,). This should open your User Settings as a JSON file. Add the following to your file

"trim_trailing_white_space_on_save": true

That’s it. You’re good to go.

sublime text settings

SSL Client Authentication in Node.js

A couple of years ago, I wrote a blog post about configuring nginx to use SSL client certificate authentication. It is to this day one of my most popular posts in terms of traffic. Since then, I’ve continued to advocate the use of client certificates as a form of authentication when your security requirements are a bit more stringent.

Recently, Node.js has piqued my interest. Most other languages/frameworks targetted for web development sit on top of a separate HTTP server (like Apache or Nginx). Node.js is unique in that it provides an HTTP server as one of the core libraries (to the shagrin of some). This means there isn’t (immediately) a need for a separate HTTP server. For fun, I decided to recreate the whole client SSL certificate authentication thing in Node.js.

If you need a refresher on how to create and sign the certs, check out the nginx post.

Turns out the more recent releases of Node.js have decent TLS/SSL support making things relatively straight forward. Here is a quick example of an HTTPS server that will allow us to perform client certificate authentication and determine authorization.

var https = require('https'),      // module for https
    fs =    require('fs');         // required to read certs and keys

var options = {
    key:    fs.readFileSync('ssl/server.key'),
    cert:   fs.readFileSync('ssl/server.crt'),
    ca:     fs.readFileSync('ssl/ca.crt'),
    requestCert:        true,
    rejectUnauthorized: false
};

https.createServer(options, function (req, res) {
    if (req.client.authorized) {
        res.writeHead(200, {"Content-Type": "application/json"});
        res.end('{"status":"approved"}');
    } else {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end('{"status":"denied"}');
    }
}).listen(443);

The first three options (key, cert, and ca) are pretty self explanitory (if they aren’t, read the previous post for a refresher). The requestCert option tells Node that it should request the client cert from a client attempting to connect. Lastly, rejectUnauthorized tells Node if it should flat out reject the connection if the certificate provided is not valid (valid meaning it must be signed by our ca, not revoked, and not expired). We’ll keep this set to false so we can make the decision in the app itself.

The https.ServerRequest object is passed to our https.createServer callback function as the first argument (named req above). Along with other information about the request (like the uri, http method, etc.), it includes some information about the client’s authorization state in the req.client.authorized attribute. This is pretty self explanitory, but this boolean attribute states whether or not the client presented a “valid” client certificate as part of its request.

We can test this out with a simple curl call.

# Denied (no cert)
curl -v -s -k https://localhost:5678

# Approved (using CA signed cert)
curl -v -s -k --key ssl/client.key --cert ssl/client.crt https://localhost:5678

There you have it. It’s a pretty trivial example, but you get the basic idea of how to get started with making client side cert authentication your authentication tier for you next Node API. All of the source code (including the example certs) is available on GitHub.

MAMP Nightmares: Fixing HTTPS After Upgrading

I use MAMP to run my local dev environment (been meaning to get a Linux VM with true LAMP going for a while but let’s face it, I’m just too damn lazy). While it’s better than the built in OS X “LAMP” support, it still is a pain. Another prime example just occurred after upgrading to MAMP 2.05 when my entire SSL configuration stop working. Here’s what I did to fix it:

  1. Get rid of all the default cruft in your ssl.conf file (this file can have different names and be found in different locations depending on your MAMP version, but basically find wherever you and get it down to something like below. While these settings probably aren’t sufficient for production, they are more than sufficient for your dev environment.

    Listen 443
      VirtualHost localhost:443
          DocumentRoot "/path/to/your/public_html/dir"
          ServerName localhost
          SSLEngine on
    
          ErrorLog "/Applications/MAMP/logs/apache_error.log"
    
          SSLCertificateFile /Applications/MAMP/conf/apache/ssl_crt/server.crt
          SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl_crt/server.key
      /VirtualHost
  2. Make sure the SSL cert and key actually exist (mine did not). However I found the old keys from my previous version and used them. If you can’t find them, just whip up another pair and remember to remove the passphrase on the key (otherwise MAMP won’t be able to start it from its GUI).

Voilá.

Httpful: The Sane PHP HTTP Client Library

cUrl is awesome. Sadly cUrl in PHP is not. More often than not, using the PHP cUrl library means digging through the curl_setopt page to figure out which poorly named constant is needed to tune our HTTP requests. Alternatives like HTTP_Request and Zend_Http aren’t much more usable or are too bloated for the common case. One evening while plugging away at some code to migrate us from BaseCamp to FogBugz, I decided I had enough. That evening Httpful came to be.

A Readable Curl HTTP Client Alternative

The goal of Httpful was simple: create a sane HTTP library focused on readability, simplicity, and flexibility – basically provide enough features to get the job done and make those features really easy to use. Before we dive into how Httpful accomplishes this, let’s start with a quick snippet:

// Fire off a GET request to FreeBase API to find albums by The Dead Weather.

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";

$response = \Httpful\Request::get($uri)->expectsJson()->sendIt();

echo 'The Dead Weather has ' . count($response->body->result->album) . ' albums.';

Okay, that looks a bit more sane than that curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); stuff. Let’s look at some of the things that Httpful has to offer.

Chaining

Anyone that has used jQuery can attest to the awesomeness and conciseness of “chaining”. Httpful allows similar chaining to neatly build up your requests. Need to specify a content-type? Tack on an HTTP body? Custom header? Just keep tacking them on to your initial request object.

Make the Important Stuff Easy

Choosing HTTP methods beyond GET and POST, quickly setting Content-Types, setting request payloads… these are the things we should be able to do quickly. This library makes those things easy using the aforementioned chaining. Let’s show a quick example doing a few of our favorite things.

$response = \Httpful\Request::put($uri)        // Build a PUT request...
    ->sendsJson()                      // let's tell it we're sending (Content-Type) JSON...
    ->body('{"json":"is awesome", "httpful": "is too"}') // lets attach a body/payload...
    ->sendIt();                        // and finally, fire that thing off!

Custom Headers

The library allows for custom headers without sacrificing readability. Simply chain another method on to your request with the “key” of the header as the method name (in camel case) and the value of the header as that method’s argument. Let’s add in two custom additional headers, X-Example-Header and X-Another-Header:

$response = \Httpful\Request::get($uri)
    ->expectsJson()
    ->xExampleHeader("My Value")            // Add in a custom header X-Example-Header
    ->withXAnotherHeader("Another Value")   // Sugar: You can also prefix the method with "with"
    ->sendIt();

Smart Parsing

If you expect (and get) a response in a supported format (JSON, Form Url Encoded, XML and YAML Soon), the Httpful will automatically parse that body of the response into a useful response object. For instance, our “Dead Weather” example above was a JSON response, however the library parsed that request and converted into a useful object. If the text is not supported by the internal parsing, it simply gets returned as a string.

// JSON
$response = \Httpful\Request::get($uri)
    ->expectsJson()
    ->sendIt();

// If the JSON response is {"scalar":1,"object":{"scalar":2}}
echo $response->body->scalar;           // prints 1
echo $response->body->object->scalar;   // prints 5

Custom Parsing

Best of all, if the library doesn’t automatically parse your mime type, or if you aren’t happy with how the library parses it, you can add in a custom response parser with the parseWith method. Here’s a trvial example:

// Attach our own really handler that could naively parse comma 
// separated values into an array
$response = \Httpful\Request::get($uri)
    ->parseWith(function($body) {
        return explode(",", $body);
    })
    ->sendIt();

echo "This response had " . count($response) . " values separated via commas";

Request Templates

Often, if we are working with an API, a lot of the headers we send to that API remain the same (e.g. the expected mime type, authentication headers). Usually it ends up in writing boiler plate code to get around this. Httpful solves this problem by letting you create “template” requests. Subsequent requests will by default use the headers and settings of that template request.

// Create the template
$template = \Httpful\Request::init()
    ->method(\Httpful\Http::POST)     // Alternative to Request::post
    ->withoutStrictSsl()              // Ease up on some of the SSL checks
    ->expectsHtml()                   // Expect HTML responses
    ->sendsType(\Httpful\Mime::FORM); // Send application/x-www-form-urlencoded

// Set it as a template
\Httpful\Request::ini($template);

// This new request will have all the settings 
// of our template by default.  We can override
// any of these settings by settings them on this 
// new instance as we've done with expected type.
$r = \Httpful\Request::init()->expectsJson();

That’s it

So that is the main gist of things. You can find the source code on GitHub. Hopefully the next time you find yourself pulling your hair out using the PHP cURL client library to connect to a third party API, maybe Httpful can come to the rescue.

Update

Finally have a landing page for the project. Checkout the Httpful PHP HTTP Client Site.

tl;dr

The PHP cURL library is ugly and unintuitive. Httpful is a sane HTTP library alternative that includes chaining, template requests, easy GPPD support, built in parsing and more. It is on GitHub.

Quickly Add and Edit Cookies In Chrome

Occasionally whilst developing, I have the need to manually set a cookie. For example, in our production environment we have multiple app servers and multiple load balancers. We follow a “round robin” approach as opposed to a “sticky session” approach when it comes to load balancing. From time to time it is really handy to be able to isolate yourself to one box for the purposes of testing/debugging a particular box. Our stack will allow this if you have a cookie telling the load balancer where you want it to take you (e.g. setting the “takeMeToServer” cookie to “app3” would hypothetically send all your requests to application box 3). After doing this the ugly way with temporary “set cookie” scripts hosted on the server I was trying to reach, I decided to look for a simpler route.

Chrome has awesome Developer Tools. Included in these tools is the handy “Resources” section which lets you inspect and delete your existing cookies for the site you are on. Unfortunately, it does not let you add or edit your cookies. This is where the old javascript: protocol comes in handy. You can use the URL bar and javascript to set a new cookie for a particular page.

Steps

  1. Navigate to the site where you wish to set a new cookie
  2. In your URL bar enter javascript:document.cookie="myCookieName=myCookieValue" where myCookieName is the name of the cookie you wish to set, and myCookieValue is the value.

Bam you are done. You may be taken to a new screen that echos out the contents of your cookie, however if you go back to the domain where you set the cookie, you should be able to open up the Developer Tools again and see your newly set cookie.

Now ain’t that sweet?

If you need to set the same cookie or two repeatedly, I would recommend adding a “bookmarklet” for your javascript above. They work just as nicely for the javascript protocol as they do for regular old http links.

Software Engibeering: Recruiting Revisted

One of my many responsibilities at ShowClix is to recruit software engineer folk for the team. It’s one of my favorite and yet most frustrating tasks. If your name isn’t Google or Facebook, if you aren’t located in “the valley”, if your pockets aren’t infinitely deep, recruiting talented engineers can be a challenge.

Even in a down economy software engineering remains a “recession-proof” job. The good software engineers are working. This is most evident by the fact that the applicant list for our Software Engineer position is only a fraction of the size of the 800 or so new applicants competing for our recent Customer Care Representative opening.

The Usual Approach

There are two common options when it comes to hiring a software engineer:

  • Throw a listing out on Craigslist/Monster/Dice/Stack Overflow Careers/Reddit Jobs and wait for the fish to bite
  • Hire a recruiting agency to do the head hunting for you

While the latter option may work great for some companies, I personally find the business model behind recruiting agencies fundamentally flawed (but that’s for another blog article). For this and other reasons I tend to stay away from them.

As a result, we’ve historically went with the route of posting on various free and paid job boards. Résumés would trickle in – with most of the candidates being what I like to call “extra mediocre”. We’d sift through the candidates, send out a “code puzzle” or setup a phone screen with the folks we thought looked promising, and eventually bring a couple of people in for an on-site.

The process was long, ineffective, and costly. Hiring should be an exciting time for a small company but with this approach it became monotonous. For this reason, when it came time to hire another software engineer, we decided to try something a bit different.

Beer Me

Instead of shelling out the $300 to $400 per job listing, we decided we’d take that money and invest it in something that was a little more fun: beer. We would throw a free event for like minded tech folk in the area to meet the ShowClix team, see the offices, and drink some delicious local craft brew. Seeing as we’re in the business of helping people throw successful events, we figured if anyone could pull it off, it should be us.

The Goals

  • Spend no more than the cost of a job listing (~$300)
  • Attract 50 local people from the Industry
  • Turn it around in one week
  • Come away with 5 to 10 really solid recruiting leads
  • Promote ShowClix as a “tech contender” in the city of Pittsburgh

The Strategy

  • Leverage what we’ve got: Let people see our awesome office packed with fun perks and a great view of the city and let them meet our young, fun, and bright team.
  • Get delicious local craft beer: There seems to be a correlation between software engineers and drinkers of quality beer.
  • Use our own platform to ticket it: Let them experience our product first hand. Turn on mobile ticketing and let them see why our product is different than what they may be accustomed to.
  • Don’t make it seem too much like a recruiting event: We wanted to attract a mixed crowd of people from the tech world, including those that weren’t looking for a job.
  • Reach out to local groups: We got in touch with the local schools (CMU and University of Pittsburgh), contacted various language specific “Meetup” groups, sent personalized emails to a handful of local active github users, and posted on the local subreddit.

The Results

We came up just short of our goal of 50 people but were quite pleased with the turnout. A few of the takeaways from our engibeering event:

  • Informal Speed Interviewing: Having all the candidates in one spot let us conduct informal preliminary interviews and cut out the need for phone screening.
  • Relaxed Atmosphere: Interviews can be intimidating. I can recall at least one horrible interview experience with a larger tech company where I felt so out of my element and flustered that I completely flubbed the interview. Getting some food and a beer or two in your candidates should help them cool the nerves a bit.
  • Turn Around Time: Going the job posting route takes a lot of time (wait for the resumes to trickle in, review, schedule screens, etc.). On that night alone we were able to “screen” many qualified candidates and walk away with several very promising leads.
  • Street Cred: As we had hoped, we got a decent mix of people actively looking for employment, people happily employed in the industry, graduate students, and those that were just curious about ShowClix. As a result, we were able to further promote ShowClix as a contender in the local tech space.
  • A Group Thing: The existing software team had the chance to meet with the candidates and play a part in deciding which candidates we would pursue. This is something that is usually done very late in the interview process or sometimes not even done until the new hire walks in on day one. Getting the gang involved early on was a major benefit.

All in all, we chalked it up as a win. We met a lot of bright, talented locals and found some quality candidates for our job opening. Best of all, the whole team had a ton of fun doing it. I’m hoping that this can become a regular occurrence.

UPDATE We just finished our most competitive round of hiring and we’re happy to announce @tomschlick will be joining the ShowClix team. Pleased with our Engibeering experiment. My only regret is that I couldn’t hire a few more of this round’s candidates. Cheers!

TextMate Won't Launch

My MacBook Pro’s battery died sometime last night whilst I was painfully watching the performance of my Pitt Panthers in the NCAA tournament. This morning when I booted it up again, TextMate would not launch. A quick Google search revealed no help. So I dug around in the ~/Library/Application Support directory to see if TextMate had left some dirty laundry there. Sure enough, a TextMate.pid file existed there. Most of the time when a .pid file exists for an Application that isn’t running, that isn’t a good thing. I deleted it. TextMate now launches.

tl;dr

If TextMate won’t open for you after not shutting down properly:

  1. Go to the ~/Library/Applications Support/TextMate directory
  2. Delete the TextMate.pid file

Javascript Prototypal Object Oriented Programming in Practice

I recently wrote a post about my Javascript Prototypal Object Oriented Enlightenment. In that post I discussed how I learned to break my Classical Object Oriented habits and stop forcing Javascript to do something it really wasn’t suited to do. I focused more on my process of transitioning from failed Class-based OO attempts in Javascript to Prototypal Enlightenment and the differences between the two approaches.

I wanted to follow up that post with a post focused on the implementation and use of Prototypal OO in Javascript. We’ll start with the short function that inspired the last post and allows for easier Prototypal OO in Javascript…

function extend(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

With this function we can easily create new objects from existing objects (this is the heart of Prototypal OO Javascript). Let’s see it in practice.

Instantiation: The Prototypal Way

Using this extend method we created, we create a new object nathan, that inherits all of it’s behavior from Person.

// Define a Person as an Object Literal
var Person = {
    name: null,
    sayName: function() {
        alert(this.name);
    }
};
var nathan = extend(Person);
nathan.name = "Nathan";
nathan.sayName();

We’ve just created a nathan object from another object, Person. In classical terms, we would be tempted call Person a “class” and we would call the process of creating nathan instantiation. We are going to stay far away from those terms. Person is a fully functional object itself (this will come in handy when we discuss “static” methods in Prototypal OOP). Secondly, we aren’t so much instantiating nathan from a class as we are cloning it from an existing prototype object.

Inheritance: The Prototypal Way

So we now have an example of Prototypal’s version of “object instantiation”. What about subclassing aka inheritance? In my previous post, I mentioned that in Prototypal OOP inheritance and instantiation are the same thing. Let’s consider this example…

var Animal = {
    kingdom: "Animalia"
};

var Dog = extend(Animal);
Dog.genus = "Canis";
Dog.speak = function() {
    console.log("Bark bark!");
};

var Sparky = extend(Dog);
Sparky.speak();

Notice that the process for creating Dog is the same process we used above for creating sparky. The only exception is that we added some behavior to Dog after we created it from the Animal prototype.

Improving extend

Relying on a single global function extend isn’t a great idea. We can tidy it a bit by tying it into the Object prototype. Object is the object from which all objects are initially “extended” from. If don’t explicitly set an object’s prototype (or implicitly through our extend method), it’s prototype will be Object.

Object.extend = function() {
    function F() {}
    F.prototype = this;
    return new F();
};

var nathan = extend(Person); from our first example,can now be written as var nathan = Person.extend();.

// Define a Person by extending Object
var Person = Object.extend()
Person.name = "John Doe";
Person.sayName = function() {
    console.log();
};

var nathan = Person.extend();
nathan.name = "Nathan";
nathan.sayName();

Another note: you may be tempted to add this to add this method to Object.prototype but beware! Extending native types can get you in trouble, in particular when using objects as dictionaries.

Now our code is a bit more OO and a bit more readable. Also, Object serves as a namespace for our method, adding additional encapsulation.

Improving extend for “Inheritance”

You’ll notice that in our Animal/Dog example, creating Dog was still a multi-step process. We extended Animal and then added behavior with a sequence of assignments. We can improve this process by modifying our extend function to take an optional object parameter that defines the before unique to our new class (in this case Dog).

Object.extend = function (def) {
    var F = function() {};
    F.prototype = this;
    return typeof def == "object" ? $.extend(true, new F(), def); : new F();
};

Note: This snippet uses the jQuery extend method which merges two objects into a new object. You can certainly get away with writing this functionality yourself if you don’t want to include jQuery.

Our definition for Dog now looks something like this:

var Animal = Object.extend({
    kingdom: "Animalia"
});

var Dog = Animal.extend({
    genus: "Canis",
    speak: function() {
        console.log("Bark bark!");
    }
});

var Sparky = Dog.extend();
Sparky.speak();

Now we can extend and add behavior in one single step. We are now left with a clean, readable way to accomplish both “instantiation ” and “inheritance” in one single step.

This last version of the extend method is closest to the one I’m currently using. I have a short boot.js file that contains this function as well as a few other helper methods that I commonly use. Another one of the methods included in this boot.js file is one that I use to easy support mixins in javascript. I’ll be following up with a post on Mixins in Javascript and how to accomplish “static methods” in Javascript over the next week or so.

Filed under  //   ecmascript   javascript   object oriented   object oriented programming   oop   programming   prototypal   prototype  

Redis CLI Select Port and Host

This wasn’t immediately obvious to me from any READMEs or docs I looked at (although it’s rather standard convention in hindsight): you can change the port and host on for the redis-cli tool via -p and -h

./redis-cli -p 8989 -h 127.0.0.1

Verify with a ping…

redis> ping 
PONG 
redis>

Hopefully this saves someone a few hairs on their head or a few google searches.

Finally Grasping Prototypal Object Oriented Programming in Javascript

Javascript and I have had a long love/hate relationship that dates back to my middle school days of hacking “DHTML” websites. One thing in particular that always bothered me was Javascript’s Object Oriented programming.

Most “Intro to Object Oriented Programming for Javascript” examples go a lot like this…

// Define a new "class"
function Person(name)  {
    this.name = name;
}

// And then we add some instance methods...
Person.prototype.sayMyName = function() {
    alert(this.name);
};

// And maybe another instance variable...
Person.prototype.age = -1.0/0.0; // forever young

// Instantiate
var nathan = new Person("Nathan Good");

How could they get it so wrong?! Why was the “class” a single function? Why was the class defined by several statements scattered around? Where was the encapsulation? How could I define my static methods? It just seemed wrong and ugly.

Unsatisfied with this approach, I ended up trying to find clever and cleaner solutions for OO programming in Javascript. I loved object literals. They were so simple and clean. I thought those had to be the answer. While object literals were definitely on the right track, my approach was still far from pretty…

// Futile attempt at "cleaning up" class definitions
var Person = function(name) {
    this.name = name;
};
Person.prototype = {
    age: -1.0/0.0,
    sayMyName : function() {
        alert(this.name);
    }
};
var nathan = new Person("Nathan Good");

And even worse…

// Another futile, "clever" solution
(Person = function(name) {
    this.name = name;
}).prototype = {
    age: -1.0/0.0,
    sayMyName : function() {
        alert(this.name);
    }
};
var nathan = new Person("Nathan Good");

Though these solutions were a little more encapsulated, these clever hacks still felt wrong. This was so not OO. So not Java.

And that was just it. Despite the name, Javascript is so not Java. Not even close.

Enlightenment

I knew Javascript was “prototype” based object oriented programming and I thought I knew what that meant… until I came across this snippet of Javascript from Douglas Crawford, the author of an awesome book call “Javascript: The Good Parts”:

function extend(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

Note: His initial definition used the name object, I think extend is more readable. I’m going to go Tarantino on you and jump back a little bit before explaining why this code is so eye opening.

Ditching the Dichotomy

As victims, er, I mean students of Java school and class-based object orientation teachings, we learn the dichotomy of object orientation: there are classes and then there are instances. A class defines the structure of how objects should look/behave. Instances are the examples made from those classes. Classes serve as the blueprint. Instances are the house built from the blueprints.

In Javascript’s Prototypal OOP, there is no separation. There are just objects. Now what could be more OO than that? Each new object is cloned (sort of) from an existing Object. We can then optionally transform that newly created object to make it suit our needs. This pattern of building from a prototype goes both for (in class-based terms) creating “new instances” AND creating “new subclasses”. Let’s think about that one for a bit.

In class-based object oriented programming inheritance and instantiation feel like two very different things. When defining a sub class, we are creating a new class that inherits attributes/behavior from its parent class and then tweaking it to suit that particular subclass' needs. To continue the analogy from before, we’re making a photocopy of our blueprints and tweaking them a bit. When instantiating that class, we make a new instance of that subclass and define that instance by setting its attributes or via getter/setter methods (barf).

In Prototypal OO, the act of “inheritance” and “instantiation” feel like the same process. There is no notion of a “class”. There are just objects. Person is an object. nathan, an example of a person, is an object that inherited its behavior from Person. Unlike in classic OOP where Person would be considered a class and nathan considered a class instance, Person and nathan are both objects on the same playing field.

Okay, you may be thinking, what in the hell are you talking about? No classes? Let’s jump to some examples.

Back to the Code, Sort of…

Originally here is where I intended to break down that short 3 line function that makes Prototypal OO Programming so much more streamlined. However, in the interest of staying on topic and teaching the Prototypal approach, I’m going to save that break down for another post or let you read more about it from Crawford.

Instead let’s focus on how we’ll use this short extend function to achieve Prototypal OO Bliss.

// Define a Person as an Object Literal
var Person = {
    name: null,
    sayMyName: function() {
        alert(this.name);
    }
};
var nathan = extend(Person);
nathan.name = "Nathan";

Whoa! Where is the new? Why aren’t I using .prototype? Well you kind of are, but they are now behind the scenes and they are there for good reason. Our focus here is to create a new object, nathan, that inherits all of its behavior from an existing prototype object, Person. That’s exactly what we’ve done here. Person is still an object. It is defined with our nice clean object literal syntax. By extending the Person object, nathan now has all of the characteristics of a Person. What’s even cooler is that I can add things/attributes/methods to nathan now that may not be common of all Persons! But thats for another post…

This seems weird…

If you learned OO the Java way, it should seem weird. When learning OOP, we always use real world examples. Physical things. Like people or animals. From that point on, the dichotomy is born. There are classes, typically abstract concepts like “Person”, that define structure and then there are living, breathing instances of those classes, like “Nathan Good”. When we’re setup with that mentality, Prototypal OO does not make sense. “A Person should be a class not an object!?!” you might think. That’s because we’ve coupled “object” to mean “physically existing” and “class” to mean “blueprint”. There is no need for this separation. If you are like me, it may take you a while to break that coupling.

Wrap up and Future Work

In reality the Prototypal OO approach makes OO programming much simpler and flexible. In later posts I’ll discuss how it removes the need for “static” methods and attributes, how we can handle “inheritance” with it, how it allows for the extremely popular “mixin” language feature, how we can achieve namespacing and how it easily allows for “one-offs”. I’ll also touch on my version of the three line function that makes all of this possible and how I’m now regularly using it. In the mean time, I’ll leave you with a snippet to whet your appetite that uses my prototypal OO helper functions.

I hope that, if nothing else, this has opened your eyes a bit to what “Prototypal Object Oriented Programming” really is. Hopefully I’ve even persuaded you to use this approach for your next big Javascript project.

Filed under  //   ecmascript   javascript   object oriented   object oriented programming   oop   prototypal   prototype  

About

Hacker. Tinkerer. Software Engineer. Beard-wearer.