barbarianmeetscoding

hackerz edition

The Art of Unit Testing 2nd Edition - a Barbaric Book Review

| Comments

With Barbaric Book Reviews I bring you interesting reviews and useful insights from awesome books that I have read. I also bring myself the magic of everlasting memory so that I don’t forget these tidbits of knowledge as I grow old and wither.

The Art Of Unit Testing book cover

A lot of what I know today about unit testing I learned from The Art of Unit Testing the first edition. That single book gave me such a strong foundation in unit testing that I have been able to apply the same basic principles in every environment/platform/language I have worked in afterwards. Even after reading many other books on unit testing, TDD, BDD… I always feel like these are just different sides or dimensions that stem, complete or expand things I learned in this book.

When I heard that @royosherove had written a reviewed version that addressed one of the issues that has been my biggest pain in the butt I could not resist: I had to read it.

Dev Talk Monday: Nordic.js 2014 Amazing Visual JavaScript Experiments and FRP

| Comments

Dev Talk Monday is the series that brings you awesome dev talks every Monday

Today I bring you a couple of JavaScript talks from the Nordic.js conference that was held in Stockholm a couple of weeks ago.

First, the completely unexpected (to me) yet super awesome and inspiring talk on Visual JavaScript Experiments by @hakimel. Makes you want to be as great as he is in building beautiful things with HTML, JS and CSS.

Secondly, a very gentle introduction to FRP (Functional Reactive Programming) by @sergimansilla in which he explains the limitations of asynchronous JavaScript with callbacks, then jumps briefly into promises to finally arrive to FRP and illustrate its usefulness through various interesting and eye-opening examples.

Hope you have a great week ahead of you!

Level Up Your Code-Fu With Chuck Norris

| Comments

Last Thursday I did my second talk at SWENUG (Sweden .NET User Group) Linköping, this time on developer productivity in a session titled Level-Up your Code-Fu with Chuck Norris (and ReSharper, VsVim and NCrunch). It was a blast!!

Here are the slides for your enjoyment:

And a description:

Our minds possess an unlimited potential and are, without a doubt, the best tool we have in our software development arsenal. However, the interface between our minds and the computer - hands, keyboard, editors… - is imperfect and inefficient, and prevents us from expressing our thoughts in code freely.

But worry not! Chuck Norris is here to kick some ass and help you improve how well and how fast you express yourself in code. Master tools like ReSharper, VsVim and NCrunch and breach the gap between mind and matter.

And some mental notes as advice for the future:

  • Do NOT freestyle the live code demo
  • Throwing chocolates at the audience. Good!
  • Involving the audience. Good!
  • Giving a Chuck Norris T-Shirt away. Good!
  • Do NOT hide behind the screen of your laptop after the demo.

Chuck Norris T-Shirt

Thank you very much to Kvadrat for sponsoring, @xatazhthe evil mastermind behind SWENUG Linköping – for organizing and everyone that attended and made such an awesome, engaged and collaborative audience.

Finally, this also brings to an end all the commitments for talks and hackathons and… other stuff that I have had for a while and frees some time to go back to building stuff with my company. Wiii!!!

East Sweden Hack Was a Ton of Fun!

| Comments

If you follow my blog assiduously, you may have been wondering for a while… where the heck are you?! Well…Worry not! I will tell you. For the past few weeks I have been preparing with a bunch of friends for East Sweden Hack 2014yeah, that’s a hackathon – and thus the sudden disappearance and blog-gy silence. The hackathon took place last weekend, I took a week of resting, and now here I am, full of energy and burning to write some code, articles and kick some butt.

As a soft re-start, I thought it would be nice to write a short article about my experience this year at ESH 2014, that will hopefully inspire you, dear friend, to join the next hackathon you have the chance to be at. Imagine this prospect: two days of hacking whatever you desire, however you desire, with whichever language, tools, libraries, frameworks, whateeevaaaa that you want. Use at least one API of those offered to you by East Sweden county (I am going to go with county although I have no clue how you would translate it to English. Anyhow, it is Östergötland in Swedish)… so use at least one API of those offered to you, and build something that improves in some way the life of those living in East Sweden. Sounds good right? Wait, there’s more! Food and beverages for the whole weekend, a nice and comfy venue and a prize for the winners to go and visit the Mecca of all-things-tech: Silicon Valley. Cool eh? :) Change a couple of details here and there, and I bet you have a similar event happening near you. Why not give it a try?

East Sweden Hack 2014 Logo

So, last year it was just @KPalmvik and I, a pair of lonesome bit pushers, but this year we got us some reinforcements and came back with a more complete and diverse team. Behold Team Panda!

Photo of Team Panda! From left to up to down-right to up: Erik Claesson (UX Panda), Kristofer Palmvik, Jenny Widén, Jaime González García (Kung-Fu Panda)

And this is what we built during the hackathon: Pendel Panda an awesome app to encourage commuters (and people) to take the bus by making it as easy and pain-free as possible, and by providing a willing assistant to be with them every step along the way in the form a… grumpy panda bear. XD Yeah and there was some crazy shit that we never got to implement that would have changed the life of a commuter as we know it… XD But anyhow, even though we did not get as far and high as we would have liked, it was a blast.

Pendel Panda app screenshots

  • Cool Stuff
    • Coding the whole weekend! (note that we got time to sleep between Saturday and Sunday)
    • Having a very diverse team with different skill and strengths
    • Super fun to follow the event on the twitters
    • Building something that works in such a short time
    • The organization that did an awesome job! Thank you!!
    • All the teams that built something from nothingness, from flimsy idea to working prototype
    • Using a new framework that we hadn’t used before: Ionic FTW
  • Less Cool Stuff
    • No internets the first couple of hours
    • Using a new framework that we hand’t used before. It can bring a lot of pain sometimes xD

Oh! I forgot! We did not win. Gå 2.0 won (Gå is walk in Swedish, or… go but only when you mean… actually… on foot, or almost because… planes also… gå) . The app is meant to encourage people to walk more through the use of game mechanics and by making it more social, like, “come walk with me”… or “look I am walking!”. You should have seen their video presentation… that was something… Wait! You can actually see their presentation down there (see the dropbox link):

If you want to know more about how the hackathon went, there’s a ton of information, photos, videos on the East Sweden Hack 2014 website (beware because it is in Swedish).

Have an awesome week!!! And, if you ever have the chance to go to a hackathon, don’t hesitate, just go!

Inspiration Corner: Hello World Podcast

| Comments

The inspiration corner is the space where I share talks, speeches, videos, articles, posts, whatever that helps me keep my motivation, energy and passion fresh. I hope will serve you as well as it does me.

I like to see myself like a beam of positiveness, an inexhaustible source of energy and unbending willpower. Sometimes, however, I get tired… veeery tired. In those moments, I find it is great to recharge with inspiring tales and stories of others. Like this one, the story of… every single developer on how he/she got started in writing software at the Hello World Podcast!.

The Hello World Podcast Logo

Not just another technical podcast. Shawn Wildermuth brings you his “Hello World” podcast where we learn about how your favorite developers tell their story of how they got started writing software!

hello world podcast

I was a little bit reticent against the idea of adding yet another podcast to my podcast list (I have to guard and protect my time, you know? ^ _ ^), so I held myself off from starting listening until about the podcast hit the 30th episode. Not my brightest moment that one, not at all, because this podcast is great! Go and check it out whenever you are in need of some inspiration.

Good job Shawn Wildermuth! Keep more episodes coming! :)

P.S. Everytime I hear Wildermuth it reminds of Neuromancer… Does that also happen to you? xD

Object-oriented JavaScript for C# Developers

| Comments

Through the last couple of years I have been working on improving my JavaScript-Fu. From looking down at JavaScript with contempt, I have come to love the language and its little idiosyncrasies. In this article, I will attempt to write the article I would have loved to read, the first time I set my mind to re-learn JavaScript the proper way.

I Love JavaScript

Ey You C# developer! Wanting to learn you some JavaScript? You’ve come to the right place! In this article you will learn how to map all those OOP C# concepts you have come to know and love to JavaScript, the ever growing language of the web! I will help you traverse the waters of Object-oriented programming by going through the pillars of OOP (encapsulation, inheritance and polymorphism) and trying to work out how they can be achieved in JavaScript.

Note: In this article I will use two types of code samples. Some that you can type in a text editor, and others that you can run directly in any JavaScript REPL (in the Chrome Dev Tools console for instance). In these second type of examples every line will be preceded by a > followed by the result of evaluating an statement, and that’s how you will be able to differentiate them. I recommend the Chrome Dev Tools REPL (Console) because it will let you copy/paste even the first type – biggish – code examples on the REPL.

Encapsulation

Encapsulation is the packing of data and functions into a single component.

The easiest way to achieve encapsulation in JavaScript is by using object literals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var conan = {
    name: "Conan, The Barbarian",
    "character class": "barbarian",
    hp : 200,
    weapons: [{
        name: "two-handed sword",
        type: "sword",
        damage: "2d20+10",
        material: "cimmerian steel",
        status: "well maintained",
        equipped: true
    }],
    talk: function(){ console.log("I am " + this.name + " !!!");}
}

This will look familiar to you since we also have object literals in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var conan = new Barbarian
    {
    Name = "Conan, The Barbarian",
    CharacterClass = "barbarian",
    Hp = 200,
    Weapons = new List<Weapon>
    {
        new Weapon {
            Name = "Two-handed sword",
            Type = "sword",
            ...
        }
    }
};

// Somewhere else we have the class definition
public class Barbarian{
    public string Name {get; set;}
    public string CharacterClass {get; set;}
    ...
}

However if you look closely at the JavaScript example you will notice that there’s no class identifier. What!? Welcome to the Jungle! There are no classes in JavaScript! (Although that may not hold true soon enough…).

An object literal in JavaScript is an easy way to create a single instance of an object with whichever arbitrary properties that you desire. All object literals and (all objects in JavaScript for that matter) are instances of the base Object type.

1
2
3
4
5
6
> var conan = {
    name: "conan"
};
undefined
> conan instanceof Object
true

Ok, so what happens if you want to create multiple similar objects? Do you need to instantiate them via literal objects one at a time? Nope, JavaScript provides Constructor Functions for just this purpose.

Constructor Functions

Constructor functions are JavaScript functions that allow us to create multiple instances which share the same properties. They work as a recipe for object creation and they represent a custom type (yep, this starts feeling like a class). Let’s see an example!:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Barbarian(name){
    this.name = name;
    this["character class"] = "barbarian";
    this.hp = 200;
    this.weapons = [];
    this.talk = function(){
        console.log("I am " + this.name + " !!!");
    };
    this.equipWeapon = function(weapon){
        weapon.equipped = true;
        this.weapons.push(weapon);
    };
}

Notice how the constructor, not only initializes an object with a set of values like in C#, but it also determines which properties an object is going to have. Effectively it works both as a constructor and a class definition (if we were to draw a parallelism with C#).

To create a new instance of a Barbarian we use the new keyword just like in C#:

1
2
3
4
5
6
7
8
var conan = new Barbarian("Conan, the Barbarian");
conan.equipWeapon({
        name: "two-handed sword",
        type: "sword",
        damage: "2d20+10",
        material: "cimmerian steel",
        status: "well maintained"
    });

This new instance is of type Barbarian and all its properties are publicly available:

1
2
3
4
5
6
7
8
9
10
11
12
> var conan = new Barbarian("Conan, the Barbarian");
undefined
> conan instanceof Barbarian
true
> conan instanceof Object
true
> conan.talk();
I am Conan, the Barbarian!!!
> conan.name;
"Conan, The Barbarian"
> conan.weapons;
[]

Data/Information Hiding

Information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed.

In the previous function constructor example we saw how all properties that we defined in the constructor function where publicly available. We may not want to have all our object implementation details out in the open, right? How do we then achieve private properties in JavaScript? We take advantage of closures, functions that refer to free variables from an outer scope.

We have closures in C# so I will not delve a lot on them but for this teeny tiny example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Add5 = AddX(5);
            var number = 0;
            Console.WriteLine(string.Format("Initial Number: {0}", number)); // Initial Number: 0
            number = Add5(number);
            Console.WriteLine(string.Format("Add 5 and it becomes: {0}", number)); // Add 5 and it becomes: 5
            number = Add5(number);
            Console.WriteLine(string.Format("Add 5 and it becomes: {0}", number)); // Add 5 and it becomes: 10

            var Add100 = AddX(100);
            number = Add100(number);
            Console.WriteLine(string.Format("Add 100 and it becomes: {0}", number)); // Add 100 and it becomes: 110
        }

        /// <summary>
        /// A function that creates another function that adds a given number X to another number
        /// 
        /// The returned function is a closure over the free variable 'x'. As you can see in the
        /// example above, the created function retains the value of the variable it encloses.
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Func<int, int> AddX(int x)
        {
            return number => number + x;
        }

    }
}

In JavaScript we can create a closure like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Barbarian(name){
    // this variables are only available in the scope
    // of this function.
    // Remember, in JavaScript, only functions create new scopes!
    var weapons = [],
        characterClass = "barbarian",
        hp = 200;

    this.name = name;
    this.talk = function(){
        console.log("I am " + this.name + " !!!");
    };
    this.equipWeapon = function(weapon){
        weapon.equipped = true;
        // Now we reference the weapons variable directly
        // creating a closure.
        // You cannot use this.weapons to access this variable any more
        // It is so private that the only way to access it is via closure
        weapons.push(weapon);
    };
}

Which makes the weapons, characterClass and hp variables effectively private: They are no longer accessible from the outside.

1
2
3
4
5
6
> var conan = new Barbarian("conan");
undefined
> conan.name;
"conan"
> conan.weapons;
undefined

Method Overloading

There is no such thing as method overloading in JavaScript, or at least method overloading as we know it in C#. If you define a method within an object twice, the second method will overwrite the first (ups!):

1
2
3
4
5
6
7
> var barbarian = {
    sayHi: function(){console.log("hi!";)},
    sayHi: function(){console.log("WaaaaZaaaa!");}
}
undefined
> barbarian.sayHi();
"WaaaaZaaaa!"

In fact, you can call any function with any number of arguments and JavaScript will just run with it:

1
2
3
4
5
6
7
8
9
10
11
> var barbarian = {
    sayHi: function(){console.log("hi!";)},
    sayHi: function(message, message2){console.log("hi! " + message + ", " + message2);}
}
undefined
> barbarian.sayHi();
"hi! undefined, undefined"
> barbarian.sayHi("I am Groot!");
"hi! I am Groot!, undefined"
> barbarian.sayHi("I am Groot!", "Waaaaa....")
"hi! I am Groot!, Waaaaa...."

How do we then provide support for method overloading in JavaScript? Well, we handle it in kind of a rudimentary way. Every function scope in JavaScript has a special variable called arguments, which behaves sort of like an array, but it is not an array, which contains all arguments passed to the function, and which can be used in the fashion below to mimic method overloading:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> var barbarian = {
    sayHi: function(){
        var args;
        if (arguments.length === 0) {
            console.log("hi!");
        }
        if (arguments.length === 1){
            console.log(arguments[0]);
        }
        if (arguments.length > 1){
            // this is like type casting the arguments array-like variable
            // to an actual array so that I can use the join method
            args = Array.prototype.slice.call(arguments);
            console.log("hi " + args.join(", "));
        }
    }
}
undefined
> barbarian.sayHi();
hi!
> barbarian.sayHi("I am Groot!");
I am Groot!
> barbarian.sayHi("I am Groot!", "Waaaaa....", "For Great Justice!")
hi! I am Groot!, Waaaaa...., For Great Justice!
  • Fun Fact: the length property of any function returns the number of arguments it expects (its arity). Isn’t that unexpected? XD

Object Augmentation

An interesting feature of JavaScript is that you can add or remove properties from objects at any point in time. This enables interesting object composition patterns like mixins.

You can add new properties to any object by using the . notation:

1
2
3
4
5
6
7
8
9
10
> var conan = { name : "conan"};
undefined
> conan.title = "the barbarian";
undefined
> conan.title
the barbarian
> conan.sayHi = function(){console.log("HI! I am " + this.name + ", " + this.title)};
undefined
> conan.sayHi()
Hi! I am conan, the barbarian

And remove properties by using the delete keyword:

1
2
3
4
5
6
7
8
> var conan = { name : "conan"};
undefined
> conan.name
conan
> delete conan.name
true // delete always returns true
> conan.name
undefined

Inheritance

In object-oriented programming (OOP), inheritance is when an object or class is based on another object or class, using the same implementation (inheriting from a class) or specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior). It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces.

Inheritance in JavaScript is slightly different than what we are accostumed to in C#. For one, there are no classes (ouch!), furthermore, inheritance doesn’t play as big a part in polymorphism since JavaScript is a dynamically typed language that relies in duck typing instead (as we will see in the next section). JavaScript is all about objects, and achieves inheritance not via class inheritance but via prototypical inheritance, that is, objects that inherit from other objects which act as prototypes (a sort of blueprint).

Prototypes

Every function in javascript has a prototype property that holds an object that will act as a prototype – will provide shared properties – for all objects created via that function and the new keyword. The prototype object has in its turn a constructor property that points back to the constructor function:

1
2
3
4
5
6
7
8
9
> function Barbarian(name) { this.name = name; }
undefined
> Barbarian.prototype
Barbarian {}
> Barbarian.prototype.constructor
function Barbarian(name) { this.name = name; }
> Barbarian.prototype = {}
undefined
> Barbarian.prototype

In the simplest inheritance scenario, you can create an inheritance hierarchy by setting the prototype property of a constructor function. By doing that, all objects instantiated using that constructor function will inherit properties and methods from the prototype object:

1
2
3
4
5
6
7
8
> function Barbarian(name){ this.name = name; }
undefined
> Barbarian.prototype.sayHi = function (){ console.log("Hi! I am " + this.name);}
undefined
> var krull = new Barbarian("krull");
undefined
> krull.sayHi()
Hi! I am krull

In a more common scenario you may have several custom prototypes in your inheritance hierarchy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Inheritance Hierarchy:
//   Barbarian -> DrawableGameObject -> GameObject -> Object

function GameObject(){
    // game object ctor  
}
function DrawableGameObject(){
    // drawable object ctor
}

DrawableGameObject.prototype = Object.create(GameObject.prototype);
DrawableGameObject.constructor = DrawableGameObject;

function Barbarian(){
    // barbarian ctor
}
Barbarian.prototype = Object.create(DrawableGameObject.prototype);
Barbarian.prototype.constructor = Barbarian;
1
2
3
4
5
6
7
8
9
// copy paste code from the example of the Chrome Dev Tools console
> var conan = new Barbarian();
undefined
> conan instanceof Barbarian
true
> conan instanceof DrawableGameObject
true
> conan instanceof GameObject
true

It is important to note that each property defined in the constructor function will be part of every single object instance, whilst each property defined in the prototype will be shared amongst all object instances. Again:

  • constructor properties and methods are defined in each instance
  • prototype properties and methods are only defined in the prototype. This emulates static variables properties. Methods can still refer to a particular instance by using the this keyword.

A common idiom to avoid needing to write the Function.prototype.property each time you want to update the prototype is to assign the prototype to a new object:

1
2
3
4
5
6
7
8
9
10
11
12
13
> function Barbarian(name){ this.name = name; }
undefined
> Barbarian.prototype = {
  constructor: Barbarian
  sayHi: function(){console.log("Hi! I am " + this.name);}
}
undefined
> var conan = new Barbarian("conan");
undefined
> conan.sayHi()
Hi! I am conan
> conan instanceof Barbarian
true

In summary once more, because this was weird as hell the first time I saw it, to emulate a C# class you would need to create a constructor function that will contain the specific properties of each particular instance and a prototype that will provide a series of shared methods and static members that will be shared across of all instances of a given type.

A C# class is equivalent to a javascript constructor and prototype pair

The Prototype Chain

When we use prototype inheritance as a method of code reuse, to reduce duplication and optimize memory, a prototype chain is built between object and the different prototypes in the inheritance hierarchy. When we call a method on a particular object instance, the JavaScript runtime tries to find that method in the object itself and if it can’t find it, it follows the prototype chain until it does:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> function Barbarian(name){this.name = name;}
undefined
> Barbarian.prototype.ravage = function(){console.log(this.name + "attaaaaack!!");}
undefined
> var conan = new Barbarian("conan");
undefined
> conan isintanceof Barbarian
true
> Barbarian.prototype.isPrototypeOf(conan)
true
> conan.ravage === Barbarian.prototype.ravage
true
> conan isintanceof Object
true
> Object.prototype.isPrototypeOf(conan)
true
> conan.toString === Object.prototype.toString
true

In the example above, we can appreciate how within the conan object instance, the ravage method is part of the Barbarian.prototype and the toString method is part of the Object.prototype.

JavaScript prototype chain

Differentiating Between Object Properties and Prototype Properties

In order to know whether a property is part of the object itself or part of the prototype you can use the hasOwnProperty method:

1
2
3
4
5
6
7
8
9
10
> function Barbarian(name){this.name = name;}
undefined
> Barbarian.prototype.ravage = function(){console.log(this.name + "attaaaaack!!");}
undefined
> var conan = new Barbarian("conan");
undefined
> conan.hasOwnProperty("name")
true
> conan.hasOwnProperty("ravage")
false

Object Augmentation in Prototypes

In the same way we used object augmentation to add new properties to an object, we can use the same concept to add new properties to a prototype and, hence, make those properties available to any object that has that prototype:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> function Barbarian(name){this.name = name;}
undefined
> var conan = new Barbarian("conan");
undefined
> var logenNinefingers = new Barbarian("The Bloody Nine")
undefined
> var shivers = new Barbarian("Caul Shivers");
undefined
> shivers.ravage
undefined
> Barbarian.prototype.ravage = function(){console.log(this.name + " attaaaaack!!");}
> conan.ravage()
"conan attaaaaack!!"
> logenNinefingers.ravage()
"The Bloody Nine aattaaaaack!!"
> shivers.ravage()
"Caul Shivers attack!!"

And so, we can see how after adding the ravage method to the prototype, instances of Barbarian that had been created previously, suddenly and auto-ma-gi-ca-lly get a new method. :O

Method Overriding

In order to override a method in JavaScript you will need to provide a new implementation of the method in your constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> function Barbarian(name){
    this.name = name;
}
undefined
> var conanTheBarbarian = new Barbarian("Conan The Barbarian");
undefined
> conanTheBarbarian.toString()
"[object Object]"
> function Barbarian(name){
    this.name = name;
    this.toString = function(){
        return "Barbarian: " + name;
    };
}
undefined
> var conanTheDestroyer = new Barbarian("Conan The Destroyer!!!");
undefined
> conan.toString()
"Barbarian: Conan The Destroyer!!!"

Or in one of the prototypes in the prototype chain:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> function Barbarian(name){
    this.name = name;
}
undefined
> var conan = new Barbarian("Conan The Barbarian");
undefined
> conan.toString()
"[object Object]"
> Barbarian.prototype.toString = function (){
        return "Barbarian: " + name;
};
undefined
> conan.toString()
"Barbarian: Conan The Destroyer!!!"

This is called shadowing just like in C#. Additionally, you can call your base prototype method by making use of JavaScript apply and call functions as illustrated in the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Create an inheritance hierarchy:
//   BarbarianKing -> Barbarian -> Object
function Barbarian(){
    this.title = "the Scavenger from the Highlands"
}
Barbarian.prototype.warCry = function(message){
    console.log(message);
    console.log("Waaaaaaaaaaahhhhh!");
};

function BarbarianKing(){
   this.title = "the King of Thieves";
}
BarbarianKing.prototype = Object.create(Barbarian.prototype);
BarbarianKing.prototype.constructor = BarbarianKing;

// Override method warCry and call method from super prototype
BarbarianKing.prototype.warCry = function(message){
    Barbarian.prototype.warCry.call(this, message);
    console.log("I am the " + this.title + "!!!!");
};
1
2
3
4
5
6
7
8
9
10
11
12
// execute previous file by copy-pasting on chrome dev tools console
> var conan = new Barbarian()
undefined
> conan.warCry("Good morning, how are you doing good sir? Now Die!")
Good morning, how are you doing good sir? Now Die!
Waaaaaaaaaaaaaaaaah!
> var kingConan = new BarbarianKing()
undefined
> kingConan.warCry("!!!!hhhhhhaaaaaaW")
!!!!hhhhhhaaaaaaW
Waaaaaaaaaaaaaaaaah!
I am the King of the Thieves!

If you are not familiar with the apply and call methods, you just need to know that they let you call a function and explicitly specify the object that this will refer to within the scope of the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> var conan = {
    name: "conan",
    sayHi: function(message){console.log(message + " " + this.name);}
}
undefined
> var logen = {
    name: "logen"
}
undefined
> conan.sayHi("hello I am")
hello I am conan
> conan.sayHi.call(logen, /* message */ "hello I am")
hello I am logen
> conan.sayHi.apply(logen, /*arguments*/["hello I am"])
hello I am logen
> conan.sayHi("hello I am")
hello I am conan

In the previous example you can see how, even though we have defined the sayHi method in the conan object, by using apply and call we can borrow the method and use it on a different object logen. For additional information, take a look at the awesome MDN docs on apply and call.

Emulating Classical Inheritance in JavaScript

Building on what we have learned so far, we can emulate classical inheritance as we known it in C# by:

  1. Making use of prototypical inheritance to ensure that any instance of an object inherits methods from its prototypes
  2. Making sure that each constructor function calls its base type constructor function using call or apply so that any instance of an object contains all properties defined in each and every constructor.

I’ll illustrate this through an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Inheritance Hierarchy:
//   Barbarian -> DrawableGameObject -> MobileGameObject

function Position(x,y){
    this.x = x;
    this.y = y;
}
Position.prototype.toString = function(){
    return "[" + this.x + "," + this.y + "]";
}

function MobileGameObject(position){
    this.position = position;
}
MobileGameObject.prototype.move = function(newPosition){
    console.log("moving " + this + " to " + newPosition);
    this.position = newPosition;
}

function DrawableGameObject(position, sprite){
    // call base type constructor function
    MobileGameObject.apply(this, position);
    this.sprite = sprite;
}
// establish prototypical inheritance 
// between DrawableGameObject and MobileGameObject
DrawableGameObject.prototype = Object.create(MobileGameObject.prototype);
DrawableGameObject.prototype.constructor = DrawableGameObject;
DrawableGameObject.prototype.draw = function(){
    console.log("drawing sprite: " + this.sprite);
    // draw sprite
};


function Barbarian(name, position, sprite){
    // call base type constructor function
    DrawableGameObject.call(this, position, sprite);
    this.name = name;
}
// establish prototypical inheritance 
// between Barbarian and DrawableGameObject
Barbarian.prototype = Object.create(DrawableGameObject.prototype);
Barbarian.prototype.constructor = Barbarian;
Barbarian.prototype.toString = function(){
    return this.name + "!!!";
};
1
2
3
4
5
6
7
// copy paste code from the example of the Chrome Dev Tools console
> var conan = new Barbarian("Conan", new Position(0,0), "conan.jpg");
undefined
> conan.move(new Position(5,5))
moving Conan!!! to [5,5]
> conan.draw()
drawing sprite: conan.jpg

Polymorphism

*Polymorphism* allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T

Polymorphism in JavaScript will be the least of your problems. As a dynamically typed language, JavaScript exhibits what is known as duck typing, whereby an object’s semantics are based on the object’s own methods and properties and not on the inheritance chain or interface implementations (like in C#).

But this is probably best illustrated through an example. Imagine a roguelike RPG, and a game scene with our mighty hero bravely venturing herself inside an eery dungeon, risking her life for adventure and profit, turning a corner into a host of ravenous ghouls…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function Character(name){
    this.name = "",
    this.draw = function(){ // draw a character }
}
function Zombie(){
    this.eatBrains = function(){ // mmmmm braaains }
    this.draw = function() { // draw a zombie }
}
function Skeleton(){
    this.creepyLaugh = function(){ // muhahahaha }
    this.draw = function() { // draw a skeleton}
}
// etc

var redSonja = new Character("red sonja");
var zombie = new Zombie();
var skeleton = new Skeleton();
// etc

var scene = {
    entities :[
        redSonja, ghouls, zombie, skeleton, orc, dragon, priest, warlock, walls, pottery, tapestries
    ],
    draw() : {
        entities.forEach(function(entity){
            entity.draw(); // duck typing style polymorphism right here
        });
    }
}

So, as long as an object has the draw method, it will behave as something that can be drawn regardless of inheritance. And thus the popular saying that you may have heard in the past…

If it walks like a duck, swims like a duck and quacks like a duck, I call it a duck.

Appendix A. Classes in JavaScript, Welcome ECMAScript 6

Somewhere above in this article I said something like “… there are not such thing as classes in JavaScript…” and I was telling the truth. You may be interesting in knowing that classes are a part of the specification of the next version of JavaScript – ECMAScript6 Harmony.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MobileGameObject {
  constructor(position) {
    this.position = position;
  }
  move(newPosition) {
    // draw sprite
  }
}

class DrawableGameObject extends MobileGameObject {
  constructor(position, sprite) {
    super(position);
    this.sprite = sprite;
  }
  draw() {
    // draw sprite
  }
}

class Barbarian extends DrawableGameObject {
  constructor(name, sprite) {
    super(new Position(0,0), sprite);
    this.name = name;
  }
  toString(message) {
    //...
  }
}

It looks awesome, doesn’t it? (Even though it is just syntactic sugar over all the concepts you have seen in this article).

For more information regarding ECMAScript 6 Harmony take a look at @lukehoban great summary at GitHub

Appendix B. A Note About this in JavaScript

To us C# developers used to the reliable value of this, JavaScript can be a little bit crazy and confusing. The only thing you need to know to be able to use this without fear in JavaScript is to forget how it works in C# and understand the following:

The `this` parameter refers to an object that’s implicitly associated with the function invocation as is termed the *function context*. (…)

(…)as it turns out, what this parameter points to isn’t, as in Java, defined by how the function is declared, but by how it is *invoked*.

Secrets of The JavaScript Ninja - The “this” parameter

So:

  • If a function is invoked as a method in the context of an object (e.g. conan.sayHi()) this will point to the object itself. (Like in C#)
  • If a function is invoked as a function (e.g. helloWorld()) this will be set to window. If you are using strict mode ("use strict";), this will be undefined saving you from unexpected errors.
  • If a function is invoked as a constructor with the new keyword then this will be a new object.
  • If a function is invoked with call or apply we can set the this to point at whatever our heart desires
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> var conan = {whosThis : function(){console.log(this);}}
undefined
// 1) invoke as a method
> conan.whosThis()
Object {whosThis: function}
// 2) invoke as a function
> var whosThis = conan.whosThis
undefined
> whosThis()
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object}
// 3) invoke as a constructor
> var o = new whosThis();
conan.whosThis {}
// 4.a) invoke with call
> whosThis.call({a: "1", b: "2"})
Object {a: "a", b: "b"}
// 4.b) invoke with apply
> whosThis.apply({a: "1", b: "2"})
Object {a: "a", b: "b"}

For more detailed information about the uses of this in JavaScript visit the MDN documentation. In addition to the above, you can use the bind method to create functions that are for ever bound to a specific object.

In Closing

So finally! Now that you are able to master the unwieldy JavaScript OOP arcane and take advantage of all the freedom and craziness this beautiful language has to offer, go off and build something awesome!

Fare thee well friend! ^ _ ^

Awesome Resources To Learn More About OOP in JavaScript

Special Mention

Principles of Object Oriented JavaScript cover

Other Awesome Resources

P.S.1. I had envisioned writing something more about higher level constructs to organize your code, and common design patterns, drawing parallels to the .NET world but I fear this article would have become undesirably long. I hope you will share my opinion and won’t be to hard on me if I leave it for a future article.

P.S.2. Still Not Liking JavaScript? Take a look at TypeScript then! :)

Write 30% Less Test Code With AutoFixture

| Comments

I have been following Mark Seemann for a while ‘cause this guy is as smart as it gets. He wrote a book on dependency injection, released two awesome courses on unit testing in Pluralsight, and has written the AutoFixture unit testing library (with many other contributors).

AutoFixture is a .NET library that helps you write unit tests with less code by providing:

  • Test data generators for primitive and complex types (in a constrained non-deterministic way – the data generation algorithm can be customized)
  • Test data builders for any type
  • AutoMocking of dependencies
  • I repeat, A U T O M O C K I N G of dependencies

and in words of Mark Seemann:

AutoFixture is an open source framework for .NET designed to minimize the ‘Arrange’ phase of your unit tests. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.

What does this means in terms of that application you are developing right now if you were to adopt AutoFixture just this very moment?

  • Write less unit test code
    • Bye writing mother objects
    • Bye writing your own test data builders
    • Bye to manually providing dependencies for your system under test
  • But wait Joe! There’s more!
    • By using a SUT (system under test) factory we effectively isolate all tests from changes in the SUT constructor. You will probably have handled this via factory methods, builders or fixture objects. But with AutoFixture and automocking, adding a new dependency to a constructor will not break any test!
    • Being able to automock dependencies means that you don’t need to explicitly mock/stub dependencies that are not used in a given test, which in turns means that tests become more readable, intentional and deliberate. The code that it is there takes active part in the test. All crud is removed, gone, caput.

Installing AutoFixture

You can easily start using AutoFixture in your project via Nuaet:

1
2
3
>Install-Package AutoFixture
>Install-Package AutoFixture.NUnit2
>Install-Package AutoFixture.AutoRhinoMock

Note: I am using Nunit and RhinoMocks in this article but there is support for many other testing frameworks and mocking libraries.

Where each of these packages consist in the following:

  • AutoFixture: this is AutoFixture itself
  • AutoFixture.NUnit2: this is an improved integration between AutoFixture and NUnit that allows AutoFixture to inject test data and SUT directly in NUnit Test methods
  • AutoFixture.AutoRhinoMock: this allows auto mocking of dependencies via Rhino.Mocks

Using AutoFixture

I am going to go fast like lightning through some of the interesting features provided by AutoFixture, brace yourself:

Auto Mocking SUT Dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Calculator{
  private readonly ILogger logger;
    private readonly IEmailSender emailSender;
    private readonly IArgumentParser argumentParser;
    private readonly IBellsAndWistles bellsAndWistles;

    public Calculator(ILogger logger, IArgumentParser argumentParser, IEmailSender emailSender, IBellsAndWistles bellsAndWistles){...}
    public int Add(string arguments){
     Tuple<int,int> operands = argumentParser.Parse(arguments)
       var sum = operands.Item1 + operands.Item2;

       logger.Info(string.Format("I just added a couple of numbers {0} + {1} = {2}", operands.Item1, operands.Item2, sum));
       emailSender.Send(new AdditionWasDoneNotificationEmail(operands, sum));
       bellsAndWistles.Alarm(operands, sum);

       return sum;
  }
}

[TestFixture]
public class CalculatorTests{

    private IFixture fixture;
     
    [SetUp]
    public void SetUp(){
       fixture = new Fixture().Customize(new AutoRhinoMockCustomization());
    }
     
    [TestCase("1 1",1,1,2)]
    [TestCase("2 2",2,2,4)]
    [TestCase("3 2",3,2,5)]
    public void AddTwoIntegers_ShouldPerformAddition(string arguments, int op1, int op2, int expectedSum)
    {
       // Arrange
       var argumentParser = fixture.Freeze<IArgumentParser>();
       argumentParser.Stub(p => p.Parse(arguments)).Return(new Tuple<int,int>(op1, op2));

       var calculator = fixture.Create<Calculator>();
       // Act
       var sum = calculator.Add(arguments);
       // Assert
       Assert.That(sum, Is.EqualTo(expectedSum));
    }

    // more tests

}

Test Builders For Any Type

1
2
3
4
5
6
var camilla = fixture.Build<User>()
                    .With(u => u.FirstName, "Camilla")
                      .With(u => u.SecondName, "For Great Justice")
                        .Without(u => u.Roles)
                    .Without(u => u.ParentCompany)
                      Create(); // other fields filled with data generated

Generating Test Data

1
2
3
4
// for complex types
var camilla = fixture.Create<User>(); // all fields are filled with data generated
// for primitive types
var number = fixture.Create<int>();

Note For The Intrepid: AutoFixture doesn’t work well if there are cycles in the object graph. If a complex type has cycles, you will need to tell AutoFixture to leave that property alone (OmitAutoProperties) or set it explicitely.

Integration with NUnit

If we do a full integration with NUnit we can remove the Arrange stage and inject the test data directly as arguments:

1
2
3
4
5
6
7
8
[Test, AutoData]
public void IntroductoryTest(int expectedNumber, MyClass sut)
{
    // Act
    int result = sut.Echo(expectedNumber);
    // Assert
    Assert.Equal(expectedNumber, result);
}

And even auto mock SUT dependencies:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Test, AutoData]
[AutoRhinoMockData]
public void IntroductoryTest(int expectedNumber, MyClass sut)
{
    // Act
    int result = sut.Echo(expectedNumber);
    // Assert
    Assert.Equal(expectedNumber, result);
}

// in this case you need to define a new attribute
internal class AutoRhinoMockDataAttribute : AutoDataAttribute
{
    internal AutoRhinoMockDataAttribute() : base(new Fixture().Customize(new AutoRhinoMockCustomization())){}
}

Mind Officially Blown Away. Booom… Boooom…. Mindbloooown with AutoFixture Booom… Boooom…. Booooom….

It even has testimonials. Open-source library with testimonials?!? Whatz?!?:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"I’ve introduced AutoFixture to my developers (at www.gab.de ) some time ago.
Weve been using it successfully with xunit in multiple projects all across
the .NET technology stack. We also use it for feeding dummy data to the UI
when developing prototypes. That saved us quite some time.
  - Florian Hötzinger, GAB Enterprise IT Solutions GmbH

"I have used AutoFixture for 3 years, it's a vital tool in my TDD toolbox, 
a real time-saver. Setting up maintainable and robust unit tests with
AutoFixture is easy and straightforward - highly recommendable"
  -Mads Tjørnelund Toustrup, Senior .Net Developer, d60 a/s

"Autofixture is more than just another test data generator. It helps me to
write tests faster, which are robust against changes in my production code.
Moreover, with Autofixture I can focus the tests on the behavior I want to
check which why they are easier to read and understand."
  -Hendrik Lösch, Saxonia Systems AG

It is time to Experiment Thyselve! Go NuGet Install-Package AutoFixture Now!

3 Things I Learned From Seductive Interaction Design, Creating Playful, Fun and Effective User Experiences - a Barbaric Book Review

| Comments

With Barbaric Book Reviews I bring you interesting reviews and useful insights from awesome books that I have read. I also bring myself the magic of everlasting memory so that I don’t forget these tidbits of knowledge as I grow old and wither.

I should read more UX books. We! [Developers] should read more UX books. They are filled with wondrous jewels of information about the arcane arts of psychology and human behavior, of inestimable value when crafting effective and engaging user experiences. They are also beautiful, I haven’t seen a UX/Design book that wasn’t in itself a wonderful and inviting artpiece of a book. (ehrr… Jaime, always sooo enthusiastic)

We recently started a book club and a library at work. In the book club we read a book a month and afterwards we discuss it (cool), in the library we have shared our books with each other for the betterment of the Universe and for great justice. That’s how I got to borrow this great book titled Seductive Interaction Design: Creating Playful, Fun and Effective User Experiences by @stephenanderson from my good friend (and UX whiz) Erik Claesson and Voilà! The article!

Dev Talk Monday: Architecting Large JavaScript Single Page Apps With Knockout.js

| Comments

Dev Talk Monday is the series that brings you awesome dev talks every Monday

This weekend I had the chance to see a superb talk by Steven Sanderson on building large scale SPAs (Single Page Application) with Knockout.js. This talk is invaluable if you are spending any amount of time working with Knockout.js and are looking for tips on how to bring your front-end to 2014. You will learn:

Pretty awesome.

Also pretty awesome the fact that you can see all ndc 2014 talks on vimeo (and all ndc talks from all time back to the prehistoric age)