JavaScript Singleton pattern

January 9, 2011 Leave a comment

The simplest design pattern of all would probably be the Singleton. The essence of the singleton pattern is that when you reference a singleton object from two or more clients, the exact same reference is passed back to each client.  Just to be clear, from the purist perspective, we are talking about a specific instantiation of a given class.  That should be ringing bells about now.  In JavaScript, there are no classes.  Consequently, the Singleton pattern is a triviality in JavaScript.  There are no class instantiations but rather a collection of objects (hash tables) floating around.  Our implementation of the Singleton pattern in JavaScript is now reduced to ensuring that the same object reference is picked from this collection.  How do we do that? Well, it’s as easy as the following code:

var mySingleton = {
isSingleton: true,
value: 1
};

In this code, anytime you access “mySingleton“, you are guaranteed to get the same object reference back. We’re done. That’s all there is to it…

But we can do better
The problem with using an object literal is that it is publicly visible.  The object as well as its properties can be changed by anyone at anytime – inadvertently or otherwise.  A better approach would be to wrap an instance of a singleton within a closure (see the article I wrote on closures)  In a nutshell, we’ll create a function (our closure) and declare a (private) instance variable. Consider the following code:

function MySingleton() {
var instance;

/* rewrite the constructor - called after 1st invocation*/
MySingleton = function () {
return instance;
};

/* first invocation establishes context */
MySingleton.prototype = this;

/* ensure we're creating with "new" */
instance = new MySingleton();
instance.constructor = MySingleton;

/* initialize instance here...
e.g. instance.property1 = true;
*/

return instance;
}

var s1 = new MySingleton(), s2 = MySingleton();
console.log(s1 === s2);

Using this approach, we have “privatized” our instance variable, we’ve ensured that our instance references the prototype of the initial invocation, and most importantly, we have rewritten the original function to the following:


MySingleton = function () {
return instance;
}

The original function is inaccessible, but the stack frame and its variables remain visible to our new constructor (via closure).

The only thing we have to worry about…
We can still overwrite our overwritten constructor. There is nothing that prevents our code from something like the following:

MySingleton = 3;

ECMA Script 5 has some really cool features to help us lock this down. More on that in a later post.

Also, to access our singleton object, we must invoke its constructor. In other words, our syntax must end with parenthesis remember, it is a method that’s providing our singleton functionality.

 

Categories: Javascript

JavaScript Closure

January 8, 2011 1 comment

One of the most used (intentional or otherwise), most valuable, and most misunderstood concepts in JavaScript is the principle of closure. Closure is a concept that is difficult to describe concisely in words, and it’s easy to overlook implementations in code. I’m going to throw my hat into the ring and describe closure in a way that makes sense to me.

Cornerstones
There are three fundamental tenets In traditional object-oriented programming: encapsulation, inheritance, and polymorphism. Closure is what provides the encapsulation tenet in JavaScript. I look at closure as a way to create scope and privatize objects. That’s it.

Theory
JavaScript allows functions to contain other functions and inner “contained” functions have access to variables declared in the outer function’s scope. Nothing new or earth-shattering here. The magic happens when we return an inner function to external code. This inner function STILL has access to the variables declared in the function in which it was enclosed.

Example
Consider the following code:

function outer() {
 var private = 1,
 inner;

 inner = function () {
  return private;
 }

 return inner;
}

/* test */

console.log(outer()()); // 1
console.log(private); //error - not found

Here, inner is a function declared within the outer function. Let’s refer to the inner function as our “accessor” function since as you’ll see, it provides access to our private variable outside of the scope in which it was declared.  (You may also hear the term “privileged” method)  The outer function declares a variable named private and sets it equal to one. The key is in returning the inner function to some external calling code. This external code does not have access to the variable “private“, but the function it just received does.

The two calls in the test section illustrate this. Let’s look at the first line of test code:
console.log(outer()()); // 1

Here we’re calling the outer function which returns the inner function. The empty parenthesis at the end simply invokes the returned (inner) method. As you can see, the value reported to the console is the value assigned to the private variable. Our calling code does in fact have access to this private variable via an accessor (inner) function.

The second line of test code merely proves that the calling code does NOT have direct access to our private variable.

Wrap up

Data encapsulation in JavaScript is achieved using closures.  Private variables are those which are declared within the same scope block as an accessor function.  A privileged accessor function provides external calling code access to our private variables.

Categories: Javascript

What’s up with “this”?

January 5, 2011 Leave a comment

The “this” keyword
In C#, the keyword “this” is predictable.  Everything’s an object – there’s no concept of a stand-alone (or classless) method.  This means that every method invocation must be made on an object instance of a known class.  “this” will always refer to the object of this known class upon which a method is called.  Always.  Static methods make the keyword “this” irrelevant by flagging them as errors at compile time.

Enter JavaScript
JavaScript is a bit more perilous in the way “this” is used.  In JavaScript, a function always belongs to some context (i.e. it always belongs to an object or namespace).  A global function declared on its own is actually a member function of the global namespace.  Consider a function declared as follows: (For clarity, I’m assuming a browser and the global namespace is actually that of the window object).

Example 1

function testThis() {
 console.log(this); //this refers to the window object
}

This is the same as if we had declared it as follows:

window.testThis = function () {
 console.log(this); //this refers to the window object
}

Caution ahead
Here is one example that demonstrates a definite “gotcha”.  The value of “this” within the function testThis() varies depending on how we invoke the function.  Consider the following example:

document.getElementById("myDiv").onclick = testThis;

In this case we are actually augmenting the object “myDiv” with our function.  We’re grabbing the actual object, and saying that it now has an additional method called onclick whose value is our testThis function.  Since the context in which our function is invoked is actually our div element, the result is as expected – “this” refers to the div element within our function.
Now let’s say that we add the function inline in our Html as follows:

<div id="myDiv" onclick="testThis();"></div>

In this case, the onclick method is not explicitly added to the div element as we might first guess.  (notice the absence of .onclick) Rather, it’s a pointer to our global function.  In this case, “this” refers once again to the window object.  Probably not desirable.  In my experience and for the sake of consistency, I would not declare event handlers inline.  It’s just begging for a quirky debugging session.  That’s just my opinion but I cannot foresee a need to ever do this.

Example 2

Now let’s see what can happen when we add our function to an object:

var objectLiteral1 = {
 name: "My first object literal",
 testThis: function() {
  console.log(this.name);  //"My first object literal" (Usually!!)
 }
};

now if we invoke the method like this:

objectLiteral.testThis();

The console will display the string “My first object literal”

The plot thickens
Let’s add another object to the mix:

var objectLiteral2 = {
 name: "My second object literal",
 testThis: function() {
  console.log(this.name);  //"My second object literal" (Usually!!)
 }
};

The caveat here lies in the fact that functions may be called with an implied parameter to establish scope (this).  We can (intentionally or otherwise) call one of these methods with the other as our scope.  For example, we can do something like the following:

objectLiteral1.testThis(objectLiteral2);

in which case the context (hence the “this” reference) in objectLiteral1’s testThisMethod now references the passed in objectLiteral2 and our console displays “My second object literal”.

Weird, quirky, and a little on the esoteric side, but you’re likely to encounter similar scenarios and it’s crucial to have an understanding of what’s really going on underneath the covers.
An afterthought, JavaScript’s call and apply methods (which you’ll probably see fairly often) take as their first parameter a scope object.  It’s really easy to get tripped up on this.  In the end, you need to be aware of this.  You could say that this enhances the power of JavaScript, but this is one area where I prefer the locked-down and predictable C# implementation of “this”.

In the end…

Boring but essential stuff.

Design pattern translations

January 4, 2011 Leave a comment

Are we really getting it?

Things just haven’t been the same since the publication of the GoF Design Patterns book in 1995.  Over the course of the past 15 years, we have chewed on, swallowed, and digested all that can be learned from UML renderings of the patterns defined in this book.  We have given each a tidy little name to remember them by.  We have touted their virtues in the halls of corporate America and beyond.  We have even gone so far as to lump large bodies of code that does not adhere to one of these 23 named entities into one evil group tagged “antipatterns”.  Not to discredit the book, its authors, or its readers, I can’t help but feel we missed the essence somewhere along the way.  At some point the content became rigid.  It was gospel.  We drifted away from the “pattern” in favor of the verbatim.  In saying “you need one interface with an Execute() method and five classes named x/y/z all related in a certain fashion in order to implement the command pattern”, we are forfeiting the true virtue of the book and that is to communicate a flow of events.

Talk to me baby

When you have kids, you learn to speak in code.  You just have to.  You don’t want your six-year-old hearing things you might have said seven years ago.  You say things like “why don’t we go do the laundry” and only your wife knows the real translation.  I didn’t really want to do laundry and my wife knew that.  The magic was in the fact that we gave a name to something, and we both understood it to mean as much.  Our six-year-old was none the wiser and happy to be playing Polly Pockets.  We were communicating on a level of abstraction. So goes the intrinsic value of design patterns.  The real value of these documented patterns comes to light when I’m discussing a coding problem with Keith in the hallway and he says “you know, I think something like a mediator would make that a whole lot cleaner” – and I get where he’s going with it.  Therein lies the value.  Communication of an idea.

Consider the audience

The patterns in the book use UML and code rooted in traditional object orientation.  It’s true that these approaches can be applied as is straight from the book if you’re coding in C#.  The same cannot be said if you’re developing in JavaScript.  As I alluded to in my post about rethinking inheritance, any attempt to coerce JavaScript into something that maps neatly onto an OO foundation is a mistake.  The same holds true when translating these design patterns.  The JavaScript implementations will be nearly unrecognizable to the pattern practitioner most of the time, but the flow of events will be the same.  Coming from an object-oriented background, this translation was a difficult one, but it’s manageable.  In fact, you’ll probably be delighted in the simplicity with which JavaScript provides the exact same pattern functionality.

Much more to come on this topic in future posts…

Rethinking inheritance

January 3, 2011 Leave a comment

When using inheritance in JavaScript, you’ll hear terms like “classical”, “pseudo-classical”, and “prototypal”.  You’ll see various patterns that illustrate each of these approaches.  If you’re anything like me, you’ll think in terms of C# and try to coerce JavaScript into what is familiar and in the end, you’ll be confused as hell.  I want to go over some of my “aha” moments and conclusions.  In the end, I’ll give you an inheritance example that just might be foundational enough to use for the rest of your career.  The terseness that follows is by design.  The points I’d like to share are significant enough that I don’t want to obscure them with unnecessary words.

Inheritance is just about code and data reuse – nothing more – nothing less.

Check your baggage at the door.  There are no “classes” in JavaScript.  You cannot define a template upon which you can construct an object in Javascript.  Anytime you have the urge to leverage your traditional OO inheritance knowledge, put your thumb in a vice and turn the crank clockwise 1/2 of a turn.  Repeat as necessary.  Trying to coerce JavaScript inheritance into aligning with what you know is a mistake.  I’ve made that mistake many times over.

Objects in JavaScript are simple hash tables.  In traditional OO syntax, you would never say that HashTable_B descends from HashTable_A.  Obviously, they’re just 2 different instances of the same datatype.  Just because you have a constructor function named “Shape” and another one named “Triangle” and intuitively you know there’s a relation there, don’t try to relate them.  Just stop it!  It’s just two hash tables referenced by “Shape” and “Triangle”.

Did I mention that all Objects in JavaScript are just hash tables?  Good.  We can continue.

Before jumping into some code, there is one piece of technical information that merits a solid understanding.  Every time you “new up” an object in JavaScript, that object will contain a pointer to a prototype object.  This prototype object is your friend in inheritance. You can use it to store any members or functions that you want shared across every other object that references this prototype. The real magic is in configuring “descendent” objects to point to the prototype you need them to.

Ok, here’s all the JavaScript inheritance code you’ll ever need…

/*global console: true*/ /* JSLint config */
/* This function is the heart of it all - it "news up" */
/* an object directing the prototype to the parent */
function newObjectFrom(o) {
 function F() { }
 F.prototype = o;
 return new F();
}


/* Typical base object */
var Car = function () {
 this.make = "plain Jane";
 this.wheels = 4;
 this.drive = function () {
  console.log("driving my " + this.make);
 };
};


/* Create our base class */
var car = new Car();

/* now add some contrived descendant objects */
var porsche = newObjectFrom(car);

/* augment this object as necessary */
porsche.make = “Porsche”;
porsche.horsepower = 585;

var mercedes = newObjectFrom(porsche);
mercedes.make = "Mercedes Benz";
mercedes.color = "Black";


/* and finally, take it for a test drive */
car.drive();   //driving my plain jane
porsche.drive();    //driving my Porsche
mercedes.drive();    //driving my Mercedes Benz
 

There are certainly other approaches towards inheritance in JavaScript, but consistency is key in a language that is so flexible.  Certainly don’t exclude alternative approaches if they make more sense for your particular circumstance.  I just highly recommend picking an approach and remaining true to it.

This is important!

If you adopt this approach, you’ll gain a wonderful side-effect.  You will have effectively factored out the “new” keyword from the JavaScript language.  Since all object creations are routed to the newObjectFrom(…) method, you’ll never have to “new up” an instance again.  All object instantiations will be either calls to the newObjectFrom(…) method, or explicit object literal declarations.  (more on that later).  Perhaps more importantly, you’ll never need to worry about forgetting to use the “new” keyword which can lead to difficult to debug problems manifested in unexpected global variables and curious values of the “this” reference within object methods.

Coding without a type-safety net

January 2, 2011 Leave a comment

Any mechanism that allows us to catch errors is good. The earlier the better. If a compiler sees that you’re doing something out of whack and it catches it at compile time, then Kudos to the compiler. I have to admit that I initially fell prey to the argument that JavaScript is inferior due to its lack of type-enforcement. That said, there are two questions that beg asking.

How many errors are due to data type mismatches?
After careful statistical analysis of all of the errors of my past, I concluded that 4.36% of my errors are a direct result of type mismatches. (Ok – you got me – it was a finger in the air and I guessed that it was something less than 5%). The bottom line is that this is a relatively negligible percentage of coding problems.

How effective is the type checking in my compiler?
Speaking on Visual Studio, the type-checking is pretty good, but it’s by no means infallible. In fact, the out of the box Visual Basic does NOT enforce strict data typing at all – you have to manually instruct VB to enforce this by using the Option Strict statement.  C# is a little better, but it certainly does allow you to make mistakes that are manifested only at run-time. Take for example the DataTable class and the following code:

DataTable dt = new DataTable();
dt.Columns.Add("KeyColumn", typeof (System.Int32));
dt.Columns.Add("ValueColumn", typeof(System.String));

DataRow dr = dt.NewRow();
dr["FatFingeredKeyColumn"] = "This is just wrong"; /* strikes 1 and 2 */
dr["ValueColumn"] = "Hello there";
dt.Rows.Add(dr);

This code doesn’t explicitly violate any type-safety rules, but the bolded line will certainly surprise you at run-time. You’re probably saying to yourself about now, that’s apples and oranges (or kiwi and bananas) and you’re partially right – this error is not a direct measure of type safety but it illustrates that compile time type checking is not a cure-all. You also might say “why in the heck are you not using a strongly typed data table?” And I would answer by saying “because I could”.  Nothing in the .NET Framework exists to prohibit this.  Then I would say “thank you for the segue into my last point”…

It’s our professional responsibility to learn and navigate pitfalls

As a developer/architect/software engineer, we have veritable arsenals aimed at our foot regardless of the development environment.  We’re paid to know when to re-aim and when NOT to pull the trigger.  Sure, JavaScript sacrifices type-safety, but it does so in exchange for significant expressiveness.  If you’re still not convinced, just think of the thousands of cast statements you’ve written in the past. Reminds me of John Wilkes Booth’s final words as he lay dying and staring at his hands… “useless”…

Categories: ASP.NET, Javascript

JavaScript is here to stay. Embrace it.

January 2, 2011 Leave a comment

A little bit of background

I’ve spent the last 12 years or so working with object-oriented development and embracing the lessons thrust upon me from tech evangelists on that side of the fence.  I worked with Delphi from version 1 to 6, when I was finally dragged (kicking and screaming) to the dark Microsoft side.  It really didn’t take long to embrace C# and ASP.NET as they were a stone’s throw from my Delphi roots, and the power and ease of use that they provided were undeniable.  So there I remained blissfully content and productive.  Now, enter an open mind…

Epiphanies and ramblings

  1. We have all this largely untapped processing power in our user’s browsers.  Ok, AJAX is the clear solution.  Well, AJAX is the clear solution, but certainly not on Microsoft’s terms.  The ASP.NET Ajax toolkit leaves much to be desired.  Let’s start with what is probably the most widely used tool in the tool shed – the update panel. Largely lost on many UpdatePanel users is the fact that you’re actually getting a full-page of data from the server even if your objective is to simply update some text in an update panel – not to mention that you’re running nearly the full-page life-cycle on the server.  That flies in the face of the very intention of AJAX in my opinion.  AJAX is wonderful for simple requests, simple, targeted, and concise response (e.g. JSON) and a simple DOM update.
  2. Cross-browser DOM implementations are wild beasts – few would disagree.  In their variances, they have successfully given JavaScript a horrible name.  It’s not JavaScript’s fault.  While JavaScript is not without idiosyncrasies, it does have some notions to dispel before going (more) mainstream…  It’s not a toy language used for annoying your site’s visitors with flashy crap.  It’s not a death-defying experience to work with a loosely typed language.  JavaScript is in my opinion more of an object-oriented language than say C# – which I now consider a class-oriented language.  Much more on that later.
  3. There’s no such thing as a TreeView in HTML and there’s no concept of ASP.NET on the client’s browser.  I’ve spent more time debugging these server-side abstractions aimed to “make my life easier” than it’s worth.  In the end, the browser knows three things: HTML, CSS, and JavaScript.  Everything else is a tool – some with merit, and others with mine fields.  Use cautiously and judiciously (and at your own risk).  My path to enlightenment started when I started embracing these three cornerstones as the absolute focus in my career.
  4. JavaScript libraries will ease your pain.  Pick one and abuse it!  There’s a learning curve, but with persistence comes reward.  I suggest looking into any or all of these libraries:  Dojo, jQuery, Prototype, YUI, MooTools - take the time to study them and leverage the one that’s a fit for you.  Not to be construed as an endorsement, but I have a particular fondness for with YUI .

Where I’m headed…

The bottom line is that this is an exciting time for the web.  I’m certain there are a few more billionaires-to-be in the wings – the visionaries – the ones that challenge some norms.  Often times, that vision comes from an understanding of the past.  I’m not touting myself as a visionary, but I certainly am one to challenge the norms.  In future posts, my intention is to document some of my “aha” moments as I trudge along a path from ASP.NET and OO to Web 3.0/4.0/??

Forewarning: I do have biases and they will undoubtedly surface from time to time.  I’ll make a concerted effort to keep them in check when appropriate, but I will certainly call Bullshit when I smell bullshit.

Follow

Get every new post delivered to your Inbox.