Monday, August 5, 2013

C# Classical Inheritance vs Javascript Constructor Inheritance vs Javascript Prototypal Inheritance

Most of us coming from languages with classical class-based inheritance have hard time understanding the javascript inheritance model where there are no classes.

I spent last few days scratching my head over and over and reading tons of different tutorials and finally I believe I grasped the idea. This blog entry is then not only a note of my attempts but also, hopefully, yet another perspective that is possibly useful to someone who has similar problems with understanding the javascript inheritance.

Classical inheritance – C#

Let’s start with an example of classical inheritance in C#. There is a class with public and private data and a subclass which inherits some properties and wants to call base class’ members. Also we want the type system to be aware of types and properly recognize whether or not an instance belongs to a particular type. Specifically: an instance of the base class should not be recognized as and instance of the child class but the instance of the child class has both the child type and base type.

class Program
{
    static void Main( string[] args )
    {
        Person p = new Person( "jan", "kowalski" );
        Console.WriteLine( p.ToString() );
        Console.WriteLine( p.GetPassword() );
 
        Person p2 = new Person( "jan2", "kowalski2" );
        Console.WriteLine( p2.ToString() );
        Console.WriteLine( p2.GetPassword() );
 
        Worker w = new Worker( "tomasz", "malinowski", 42 );
        Console.WriteLine( w.ToString() );
        Console.WriteLine( w.GetPassword() );
 
        Console.WriteLine( p is Person );
        Console.WriteLine( w is Person );
 
        Console.WriteLine( p is Worker );
        Console.WriteLine( w is Worker );
    }
}
 
// class
public class Person
{
    // public data
    public string name;
    public string surname;
 
    // public constructor
    public Person( string name, string surname )
    {
        this.name    = name;
        this.surname = surname;
 
        this._password = name;
    }
 
    // public method
    public override string ToString()
    {
        return name + " " + surname;
    }
 
    // private data
    private string _password;
 
    // public method to expose private data
    public string GetPassword()
    {
        return this._password;
    }
}
 
// a subclass
public class Worker : Person
{
    private int salary;
 
    // public constructor calls base class constructor
    public Worker( string name, string surname, int salary )
        : base( name, surname )
    {
        this.salary = salary;
    }
 
    // overridden method calls base class method
    public override string ToString()
    {
        var ps = base.ToString();
        return ps + " " + salary.ToString();
    }
}

The output of this code is

jan kowalski
jan
jan2 kowalski2
jan2
tomasz malinowski 42
tomasz
True
True
False
True

Inheritance in JavaScript

I’ve found these tutorials to be helpful:

  1. Why Prototypal Inheritance Matters by Aadit M Shah
  2. Private Members in Javascript by Douglas Crockford
  3. Classical Inheritance in Javascript by Douglas Crockford
  4. Why I don’t use Prototypal Inheritance in Javascript by Sam Elsamman

Start by reading these and come back when you finish.

It turns out that it is not the prototype notion that caused me most probles but rather the fact that there are two possible approaches to inheritance in JavaScript: the constructor inheritance and prototypal inheritance. The remaining part of this entry shows differences between these two – I will show how the above C# snippet converts to JavaScript for both approaches.

Constructor inheritance – JavaScript

The constructor inheritance is a technique where a function, whose name starts with an uppercase letter by convention, acts as a constructor. You have to remember to call it with new to get a new instance. The newly instance “inherits” properties from a so called prototype chain which basically means that there is a list of known instances which play the role of prototypes.

The notion of the prototype is not new in classical object-oriented languages, the Prototype pattern is a well known design pattern. There is a similar concept behind both Prototype pattern in C# and prototype notion in Javascript:

  • in a Protype design pattern you have a prototype instance of an object and you use to create new objects out of by cloning the prototype
  • when creating a new instance out of a javascript prototype, the runtime does not clone the object but stores the instance of the prototype in a private field of the newly created instance and uses the prototype to resolve members which are not available on the newly created instance.

Since the newly created javascript instance has its prototype which has its prototype which has its prototype …. the runtime is capable of an arbitrary level of “inheritance” just by walking up the inheritance chain. And just like in C# everything ultimately leads to the Object class, the prototype chain in Javascript ultimately ends with …. Object.prototype.

The constructor inheritance snippet is:

// a public constructor
function Person( name, surname )
{
  // public members
  this.name = name;
  this.surname = surname;
  
  // a private member
  var _password = name;
  // a method to retrieve the private member
  this.getPassword = function()
  {
     return _password;
  }
}
 
// a public instance method
// has to use "this" otherwise members are not available
Person.prototype.toString =
  function()
  {
     return this.name + ' ' + this.surname;
  }
  
var p = new Person( 'jan', 'kowalski' );
console.log( p.toString() );
console.log( p.getPassword() );
 
var p2 = new Person( 'jan2', 'kowalski2' );
console.log( p2.toString() );
console.log( p2.getPassword() );
 
// a subclass
function Worker( name, surname, salary )
{
  // calls the public constructor of the base class
  // using .call and passing "this" as a first argument
  // so that it binds to "this" in the called constructor
  Person.call( this, name, surname );
  this.salary = salary;
}
 
Worker.prototype = new Person();
 
// override the public instance method
Worker.prototype.toString =
  function()
  {
     // call the base class implementation
     var s = Person.prototype.toString.call( this );
     return s + ' ' + this.salary;
  }
 
var w = new Worker( 'tomasz', 'malinowski', 42 );
console.log( w.toString() );
console.log( w.getPassword() );
 
// test the type system
console.log( p instanceof Person );
console.log( w instanceof Person );
 
console.log( p instanceof Worker );
console.log( w instanceof Worker );
Prototypal inheritance in JavaScript

Another and more modern approach to inheritance in Javascript is the prototypal inheritance. There are few subtle differences with the former approach:

  • there is no constructor function, rather there is an explicit instance of the prototype
  • instead of new we are using Object.create which creates a new instance out of the given prototype
  • instead of constructor function we have a factory method which can possibly call the factory method of the base class
  • because there is no constructor function, instances cannot be tested for being a particular type with the instanceof operator; rather – an extra method is provided
  • an auxiliary function extend is introduced which clones the prototype of the base class as the prototype of the child class
// generic "extend" method to clone prototypes
// usage:
//   childproto = baseproto.extend( new set of properties )
Object.prototype.extend = function (extension) {
     var hasOwnProperty = Object.hasOwnProperty;
     var object = Object.create(this);
 
     for (var property in extension)
         if (hasOwnProperty.call(extension, property) ||
             typeof object[property] === "undefined")
                 object[property] = extension[property];
 
     return object;
};
 
// generic "instanceof" replacement
Object.prototype.instanceof = function (prototype) {
     var object = this;
 
     do {
         if (object === prototype) return true;
         var object = Object.getPrototypeOf(object);
     } while (object);
 
     return false;
};
 
// person prototype instance
var person = {
 
  create : function( name, surname )
  {
     // call the case class factory method
     var self = Object.create( this );
     self.name = name;
     self.surname = surname;
     
     var _password = name;
     self.getPassword = function()
     {
       return _password;
     };
     
     return self;
  },
  toString : function()
  {
     return this.name + ' ' + this.surname;
  }  
}
  
var p = person.create( 'jan', 'kowalski' );
console.log( p.toString() );
console.log( p.getPassword() );
 
var p2 = person.create( 'jan2', 'kowalski2' );
console.log( p2.toString() );
console.log( p2.getPassword() );
 
// create an inherited prototype
var worker = person.extend( {
  // override the factory method
  create : function( name, surname, salary )
  {
    // call the case class factory method
    var self = person.create.call( this, name, surname );
    self.salary = salary;
    return self;
  },
  toString : function()
  {
     var s = person.toString.call( this );
     return s + ' ' + this.salary;
  }
});
 
var w = worker.create( 'tomasz', 'malinowski', 42 );
console.log( w.toString() );
console.log( w.getPassword() );
 
// test the type system
console.log( p.instanceof( person ) );
console.log( w.instanceof( person ) );
 
console.log( p.instanceof( worker ) );
console.log( w.instanceof( worker ) );
 
Testing JavaScript snippets

Both Javascript snippets can be tested in a classical way – you create an html page, reference the script and navigate to the page in a browser of your choice.

Another approach that works well for me is to run FireFox, open up an empty tab page and up the javascript console and make sure that the command line is turned on. This gives a nice interactive command line mode where any script can be pasted and executed and results are visible on the debugging console.

Thursday, August 1, 2013

My very first attempt at JSIL

I am planning to explore various possibilities of translation from high-level languages to JavaScript, following the philosophy “JavaScript = Web Assembly”. JSIL seems promising, there are some impressive demos available.

My very first attempt seems to be working. To see it in action, open up the “try JSIL” page, paste my C# code and click “Compile & Run”. Have fun.

using System;
using JSIL;
using JSIL.Meta;
 
public static class Program {
  
  public static int WJulia = 384;
  public static int HJulia = 384;
  
  public static double kat1;
  public static double kat2;
  
  public static int cx, cy;
    
  public static void Main () {
    
    dynamic document = Builtins.Global["document"];
    dynamic window = Builtins.Global["window"];
    
    var body =
      document.getElementsByTagName("body")[0];
    var canvas = document.createElement("canvas");
    canvas.width  = WJulia;
    canvas.height = HJulia;
    var ctx = canvas.getContext("2d");
    var img = ctx.createImageData( WJulia, HJulia );
 
    body.appendChild(canvas);
    
    window.setInterval(
      (Action)(
        () => 
        {
          Loop();
          Redraw(ctx, img);
        }),
      25);
  }
  
  public static void Loop()
  {
 
    kat1 += 0.017;
    kat2 += 0.021;
    cx = (int)(981 * Math.Sin(kat1));
    cy = (int)(983 * Math.Cos(kat2));
  }
  
  public static void Redraw (
    dynamic ctx, 
    dynamic img) 
  {
     
    var px = 0;
    int i = 0, j = 0;
    int x, y, x2, y2;
    int c = 0;
    
    for (i = -2304; i < 2304; i = i + 12)
    {
      var py = 0;
      for (j = -2304; j < 2304; j = j + 12)
      {
        c = 0;
        x = i;
        y = j;
        x2 = x * x;
        y2 = y * y;
 
        while (((x2 + y2) < 4000000) && (c < 31))
        {
           c++;
 
           y  = ((x * y) / 512) + cy;
           x  = ((x2 - y2) / 1024) + cx;
           x2 = x * x;
           y2 = y * y;
 
        }
 
        SetPixelColor( 
          img.data, 
          4 * (py * WJulia + px), 
          255, 
          (byte)(8 * c), 
          (byte)(8 * c), 
          (byte)(255 - c)
        );
 
        py++;
      }
 
      px++;
    }     
    
    ctx.putImageData( img, 0, 0 );
  }
  
  public static void SetPixelColor( dynamic pix, int offs, byte a, byte r, byte g, byte b)
  {
    pix[offs + 0] = r;
    pix[offs + 1] = g;
    pix[offs + 2] = b;
    pix[offs + 3] = a;
  }  
}

Wednesday, July 24, 2013

A Basic example of web site automation with TestStack.White

TestStack.White is an ancestor of old White UI Automation framework. The framework installs easily from NuGet.

To automate the web browser, we need to launch it and then automate the UI using White’s API. There are two ways to automate an application in white:

  • we can use the API to find controls in the control hierarchy and then use the API of found control to automate it (for example, the TextBox class that corresponds to input fields has the Text property with two accessors, get and set)
  • we can use the API to move the mouse and input data from the keyboard

The first method, although sounds interesting, is rather difficult when automating a web browser. The problem is that the White search API is rather limited and works better if the underlying application is a .NET application. For example, any control on the screen can be found by its .NET “name”.

In case of a native application (and browsers are not .NET applications), the only way to find a specific control is to get a complete list of controls and try to find a match programmatically. And this is why it is easier said than done. For example, trying to automate the google.com web site and searching for all visible textboxes on FireFox yields a list of 42 controls with no way of picking this correct one that should contain the search phrase.

Let’s then see the code snippet and discuss it:

var psi = new ProcessStartInfo 
{ 
    FileName  = "iexplore.exe", 
    //FileName  = "firefox.exe",
    Arguments = "http://www.google.pl" 
};
 
Application application = Application.Launch( psi );
application.WaitWhileBusy();
 
Window window = application.GetWindows().FirstOrDefault();
 
application.WaitWhileBusy();
 
// find control and input text ...
//IUIItem[] textBoxes = window.GetMultiple( 
//   SearchCriteria.ByControlType( System.Windows.Automation.ControlType.Edit ) );
//TextBox searchTextBox = textBoxes[1] as TextBox;
//if ( searchTextBox != null )
//    searchTextBox.Text = "search phrase";
 
// .. or rather simulate user input
window.Keyboard.Enter( "search phrase" );
 
window.Keyboard.PressSpecialKey( White.Core.WindowsAPI.KeyboardInput.SpecialKeys.RETURN );
 
//window.Mouse.Location = new Point( 800, 870 );
//window.Mouse.Click();

As you can see it all starts with lauching the web browser’s process. Then I am selecting the very first active window of the process and this is where things start to be messy – this works only if there are no other active instances of the same browser.

Then the commented out snippet shows how to use the API to find a text box and set its value but then it turns out that providing the input is easier if made with the Keyboard and/or Mouse objects.

Wednesday, July 10, 2013

Debugging the source code of third party components (NHibernate and others)

The .NET framework source code debugging has been received as one of the most impressive features of VS2008. Sadly, although many detailed instructions has been published (here, here, here and dozen of other web pages) it just doesn’t work.

There are probably multiple reasons for this, including the out-of-sync versions of base class libraries. People complain, open issues on Connect, ask on Stackoverflow, all this for nothing.

My initial attempt on this with VS2012 and .NET 4.5 was succesfull. I was able to debug into Console.WriteLine and other library methods and I’ve found this amazing. I think it worked for few hours and then stopped working and despite all my attempts, prayers and curses it just doesn’t work anymore.

What seems to work however, is the Symbol Source, they publish *.pdbs for multiple NuGet packages including NHibernate, Autofac, Castle or ServiceStack.

What you get then is when you register their source server in VS (follow this tutorial but point to http://srv.symbolsource.org/pdb/Public as described here), you can debug the internals of all these 3rd party components. Works like a charm.

Friday, June 14, 2013

FederatedPassiveSignIn for WIF and ASP.NET 4.5

With WIF now fully integrated into the Base Class Library, people (including myself) found it disappointing that the FederatedPassiveSignIn control (and other ASP.NET controls) has been removed from the API.

Not only this means that the migration is not easy but also it makes it more difficult to build applications which target multiple STSes.

This is my attempt to bring the FederatedPassiveSignIn back for the community.

Go to online repository and download source code.

Friday, May 24, 2013

Public Suffix List

The most obvious aspect of the Public Suffix List is that your website can’t issue cookies for any of these effective top-level domains.

For example, your web site cannot issue cookies for wroclaw.pl (since it IS on the list) but you can issue cookies for koszalin.pl (since it is NOT on the list).

In theory, the list is available from Mozilla’s site and the only question is “do all browsers respect the list”?

Wednesday, May 15, 2013

Yet Another ORM Micro Benchmark, part 3/3, results

This is the last post of the series. We introduced a micro orm benchmark with few contestants and we implemented all required tests. In this post we analyze results.

Complete set of results

Let us start from a complete set of results (all numbers are miliseconds so for example 531 means 0.531 sec and 6502 means 6.502 sec):

category

name

totalms

ADO.NET

TOP 1

144.0144

Linq2Sql

TOP 1

526.0526

EF ModelFirst NoTracking

TOP 1

531.0531

EF ModelFirst Tracking

TOP 1

551.0551

EF CodeFirst NoTracking

TOP 1

1063.1063

EF CodeFirst Tracking

TOP 1

1069.1069

nHibernate StateLess

TOP 1

654.0654

nHibernate StateFull

TOP 1

658.0658

ADO.NET

TOP 10

111.0111

Linq2Sql

TOP 10

574.0574

EF ModelFirst NoTracking

TOP 10

499.0499

EF ModelFirst Tracking

TOP 10

627.0627

EF CodeFirst NoTracking

TOP 10

1046.1046

EF CodeFirst Tracking

TOP 10

1247.1247

nHibernate StateLess

TOP 10

1194.1194

nHibernate StateFull

TOP 10

1305.1305

ADO.NET

TOP 100

270.027

Linq2Sql

TOP 100

710.071

EF ModelFirst NoTracking

TOP 100

675.0675

EF ModelFirst Tracking

TOP 100

1596.1596

EF CodeFirst NoTracking

TOP 100

1210.121

EF CodeFirst Tracking

TOP 100

2836.2836

nHibernate StateLess

TOP 100

5699.5699

nHibernate StateFull

TOP 100

6502.6502

ADO.NET

TOP 1000

1327.1327

Linq2Sql

TOP 1000

2064.2064

EF ModelFirst NoTracking

TOP 1000

1885.1885

EF ModelFirst Tracking

TOP 1000

10700.0699

EF CodeFirst NoTracking

TOP 1000

2365.2365

EF CodeFirst Tracking

TOP 1000

18658.8657

nHibernate StateLess

TOP 1000

51017.1012

nHibernate StateFull

TOP 1000

58400.8395

ADO.NET

TOP 10000

10878.0877

Linq2Sql

TOP 10000

19527.9526

EF ModelFirst NoTracking

TOP 10000

13496.3495

EF ModelFirst Tracking

TOP 10000

122345.2333

EF CodeFirst NoTracking

TOP 10000

13797.3796

EF CodeFirst Tracking

TOP 10000

210554.0533

nHibernate StateLess

TOP 10000

546423.6369

nHibernate StateFull

TOP 10000

564736.468

The most interesting comparison to me was to see how retrieving data works for different sizes of datasets. Here are results presented on charts:

General observations:

  • bare ADO.NET is of course always the fastest but for the largest dataset, EF with tracking turned off is almost as fast (which is amazing)
  • Linq2Sql is outperformed by EF Model First No Tracking and, for the largest dataset, even EF Code First No Tracking is way faster than Linq2SQL
  • EF Model First is always faster than EF Code First
  • EF with tracking is always much slower than EF without tracking. For 1000 or more records tracking can probably hurt the performance badly if you are only reading the data
  • nHibernate StateLess is always faster than nHibernate StateFull (which is expected)
  • nHibernate is surprisingly slow when larger sets are retrieved (which is rather unexpected and frankly, I wonder if there is a way to speed it up as it looks rather disappointing)

Note that benchmaring ORMs should also involve inserts/updates/deletes in various scenarios. Please consider my experiments as valid only in this specific context (data retrieval).

I would also like to hear a comment or two about this. I am especially interested in the underperformance of nHibernate for large sets of data – I wonder what else could be done to speed it up.