Tuesday 25 September 2012

Object.create and inheritance

It seems like much has been written in the last years advocating the use of Object.create over constructor functions and new. This write up by the almighty Douglas Crockford seemed to lay the foundations for this "movement". Well, I pretty much agree with Crockford in that Object.create is much more in line with the prototypical nature of JavaScript. You create an object and then decide to use it as the prototype for another object, and so on, Object.create seems a much better fit than "new constructorFuntion", a construction imported from class based languages.

However, even when I love the prototypical nature of JavaScript, and all the freedom and plasticity that it provides (modifying the prototype of a function or the [[Prototype]] of another object, creating inheritance relations "on the fly")... I'm afraid I'm too used to the class based paradigm, and in many occasions I need that approach: classes as templates for creating objects, as a way to identify what an instance is (myInstance.constructor...).

Indeed, I think JavaScript gives us the best of both worlds, we can have certain structure by emulating classes, but we have total freedom to escape those restrictions and use the prototype or [[Prototype]] to augment a "class" or instance, use traits and so on... with this in mind, Object.create for me is a useful addition, but not a replacement.

I thought it was just me that was missing something about the Object.create advantages, so finding 2 articles [1 and 2] by 2 rather respectful guys, that very closely align with my thoughts, made me feel some relief :-) The main idea in both articles is that Object.create can help us to improve the class based (constructor based) inheritance in JavaScript. Furthermore, Ben Nadel article does a very interesting exploration on how to create a "classical design" (Person-Child with instances of each one) just using Object.create, and draws the conclusion that it doesn't seem to fit well.

So, the idea from both articles is that we would continue to write constructor functions and add methods to the constructorFunction.prototype object, but would create the inheritance chain with:

Child.prototype = Object.create(Person.prototype);

instead of:

Child.prototype = new Person();

This way we avoid invoking the Person "constructor function" when setting the prototype chain, I guess in most cases this is not a big problem, but anyway it's better if we can avoid it.

There's something that both articles are missing and that I consider important, setting the constructor property of the prototype objects in the Prototype chain, that is, in old school inheritance we do:

Child.prototype = new Person();
Child.prototype.constructor = Child;

with the new approach we'll do:

Child.prototype = Object.create(Person.prototype, { constructor: {value: Child} });

This way we can use myInstance.constructor to obtain from the prototype chain the function that was used to create this instance (think of C#'s Object.GetType()). We can argue that this is very static approach of little use in such a dynamic language where irrespective of how an object was created we can freely augment it ending up with something that has little to do with the original "template" used for its creation. Yes, I rather agree, for JavaScript we should mainly think in terms of Duck typing, but well, that's a matter of choice (or style), and depending on that having the correct .constructor property can be important.

So, in the end this is how the code would look:

// Shape "class"
function Shape() {
  this.x = 0;
  this.y = 0;
  console.log('Shape constructor called');
}

Shape.prototype = {
  constructor: Shape,
  move: function(x, y) {
    this.x += x;
    this.y += y;
 console.log("moving");
  },
};

console.log("Shape.prototype.constructor.name: " + Shape.prototype.constructor.name);
var s1 = new Shape();
console.log("s1.constructor: " + s1.constructor.name);

// Rectangle "class"
function Rectangle() {
  console.log('Rectangle constructor called');
  Shape.call(this);
}
//very important, remember we have to use the new "properties syntax"
Rectangle.prototype = Object.create(Shape.prototype, {
 constructor: {value: Rectangle},
 rectangleOperation: {value: function(){
  console.log("rectangleOperation");
 }}
});

There's one interesting point mentioned in the daily.js article when they talk about Object.create as the only way to obtain an object without a prototype chain (that is, [[Prototype]] points to null). We could think of achieving the same by setting the constructorFunction.prototype to null, but contrary to what we could expect, that does not give us a null [[Prototype]] when creating an instance, but makes it point to Object.prototype. I guess it's one of those corner cases explained somewhere in the ECMAScript reference

function Shape() {
}
 
//this is pretty interesting, even if we define the Shape prototype as null, an instance object created with it ends up getting a [[prototype]], the Object.[[prototype]]

Shape.prototype = null;
var s1 = new Shape();
if (!Object.getPrototypeOf(s1))
 console.log("s1.__proto__ is null"); //prints nothing

if (Object.getPrototypeOf(s1) === Object.prototype)
 console.log("s1.__proto__ === Object.prototype"); //this is true

Finally, another interesting use for Object.create that comes to my mind, is for mapping "data objects" to "full objects". I mean, a normal object has data and behaviour, but when we sent it over the wire (let's say an Ajax call asking for JSON data) we just receive the data, so we need to map it back to a full object with also includes behaviour (we mainly need to set the [[Prototype]])

I think this example will make it clear (note the use of a fieldsToProperties function, as Object.create expects an object with properties, not just with data fields)

//interesting use of Object.create to map a "data object" returned from the server to a full object
function fieldsToProperties(obj){
 var res = {};
 Object.keys(obj).forEach(function(key){
  res[key] = {value: obj[key]};
 });
 return res;
}

//Employee "class"
function Employee(nm){
 this.name = nm;
};

Employee.prototype = {
 constructor: Employee, 
 generatePayroll: function(){
  console.log("generating payroll for " + this.name);
 }
};

//let's say I receive this Employee object via an Ajax call, so I have only data and want to add the Employee functionality to it
var e1 = {
 name: "xuan",
 age: 30,
 city: "Uvieu"
};

e1 = Object.create(Employee.prototype, fieldsToProperties(e1));

e1.generatePayroll();

Monday 24 September 2012

Some Good Films

There are some pretty good films that I've watched recently but for which I haven't felt like writing a complete review, though I thought I could list them here as sort of a tribute and in case someone reads this and feels like trying.
  • The Grey. Well, Unknown and Taken (by the way, I can't wait to grab my hands on Taken 2) have made me a huge fan of Liam Neeson. His role here is not much different, he plays a hard, good man with a troubling existence that suddenly will be confronted with a desperate situation from which he'll to escape using all his many resources.
  • The Monitor This Scandinavian film makes a cold spell descend upon you. Noomi Rapace's performance is outstanding, playing a woman in a rather hard situation. I guess I've got a weakness for (on screen) strong women drawn into a nightmare that makes them apparently fragile (both physically and mentally)... something similar to Naomi Watts in 21 Grams.
  • Red Lights Quite a brilliant film. The plot is pretty good, the development is excellent, keeping you hooked until the last minute, and the final twist is one of the best options they could have come up with. De Niro's performance is masterly, how far would you be willing to go to keep the lie on which your whole life is based?
  • Red State Interesting portrait of what could be not too far from the reality in some dark corners of USA. A sect of Christian fundamentalists hunt gays and "perverts" to death. The police take action, but far from sorting out the mess they behave like wild soulless bastards and screw up the whole thing even more. A must see.
  • And Soon the Darkness Apart from the 2 cuties starring, the film is pretty good and kept me sat in front of my laptop from the first to the last minute. One more look at how some human shits make a living off destroying others. Trust no one, be always alert.
  • Shuttle This film shares some similarities with the aforementioned one. Some shitheads trying to take advantage of some cute ladies. Pretty intense, watch it.

Thursday 20 September 2012

Well Done Guys!

This is Europe
this is XXI century
this is a secular land
this is where the Welfare state was born and this is not where it will fade away
This is a land where too much blood was shed in the name of religion, profit, borders or ethnicity
but our ancestors gained our freedom and you won't take it away.
We won't kneel before the new oppressors: fanatical Muslims, fanatical Christians, fanatical Jews, fanatical bankers, fanatical markets...
Fuck you all, we don't surrender, we fight back.

Charlie Hebdo

More Info here

Femen activist chainsaws a Cross... shit, this is like a Black Metal fantasy :-D

More Info here

Monday 3 September 2012

Overcome some dynamic limitations

I've already written here about C#'s dynamic capabilities several times (1, 2), and sure they are pretty cool and rather astonishing the first time you hear about them. Problem is that once you've passed the initial astonishment phase (there are still quite few languages that mix the static and dynamic paradigms, ActionScript and Groovy come to mind) you intend to use these dynamic features at the same level other languages have got you used to, and it's then when you're faced with several limitation. Let's see how to (sort or) circumvent them

I'm going to focus on the use of ExpandoObject's

  • Initialization syntax.
    The normal way to initialize this would be something like this (notice the usage of closures so that "methods" can have access to their "this":
    dynamic expObj = new ExpandoObject();
      expObj.Name = "Xuan";
      expObj.LastName = "Arboleya";
      expObj.PrettyPrint = (Func<string>)(() => "X" + expObj.Name + " " + expObj.LastName + "X");
      Console.WriteLine(expObj.PrettyPrint());
    

    When used to Object literals like the ones in JavaScript, the syntax above does not look much elegant. After several attempts involving lambdas or Dictionaries... I've concluded your best bet is to use the technique explained here. The use of params is something I was missing and that gives us a rather elegant syntax.

    public static KeyValuePair<string, object> WithValue(this string key, object value)
    {
        return new KeyValuePair<string, object>(key, value);
    }
    
    public static ExpandoObject Init(
        this ExpandoObject expando, params KeyValuePair<string, object>[] values)
    {
        foreach(KeyValuePair<string, object> kvp in values)
        {
            ((IDictionary<string, Object>)expando)[kvp.Key] = kvp.Value;
        }
        return expando;
    }
    
    dynamic foo = new ExpandoObject().Init(
        "A".WithValue(true),
        "B".WithValue("Bar"));
    
    
  • Ability to enumerate the properties: fields, methods (delegates) in a dynamic object.
    This is not possible out of the box cause any class implementing the IDynamicMetaObjectProvider interface can do it in a different way, so it's the class designer who has to provide that functionality. As for ExpandoObject, given that it implements the IDictionary interface, it's a matter of doing a Casting to IDictionary (it's an Explicit Interface implementation, that's why casting to ExpandoObject is not enough)
  • Ability to add/remove/get access to properties using its string name. The same reasoning explained above applies here, so cast to IDictionary

Based on my explanations above, I've put together this helper class:

public static class ExpandoHelper
{
 //all credit for these two methods to SomeDave: 
 //http://stackoverflow.com/questions/5910331/using-collectioninitializer-syntax-with-expandoobject
 public static KeyValuePair<string, object> WithValue(this string key, object value)
 {
  return new KeyValuePair<string, object>(key, value);
 }

 public static ExpandoObject Init(
  this ExpandoObject expando, params KeyValuePair<string, object>[] values)
 {
  foreach(KeyValuePair<string, object> kvp in values)
  {
   ((IDictionary<string, Object>)expando)[kvp.Key] = kvp.Value;
  }
  return expando;
 }

 
 public static IEnumerable<string> GetKeys(this ExpandoObject obj)
 {
  return ((IDictionary<string, object>)obj).Keys;
 }
 
 public static T GetValue<T>(this ExpandoObject obj, string key)
 {
  return (T)((IDictionary<string, object>)obj)[key];
 }
 
 public static void SetValue(this ExpandoObject obj, string key, Object value)
 {
  ((IDictionary<string, object>)obj)[key] = value;
 }
}

that can be used like this:

public static void Print(dynamic d)
 {
  Console.WriteLine(d.PrettyPrint());
  foreach(string key in ExpandoHelper.GetKeys(d))
   Console.WriteLine(key + ": " + ExpandoHelper.GetValue<Object>(d, key));
   
  Console.WriteLine(ExpandoHelper.GetValue<string>(d, "Name"));
  
  //Extension Methods are a compile time artifact, so, while the line below compiles, it crashes at runtime, as the dynamic dispatch mechanism can't find a GetValue property in that object
  //d.GetValue<string>("Name");
  ExpandoHelper.SetValue(d, "Name", "Antón");
  Console.WriteLine(ExpandoHelper.GetValue<string>(d, "Name"));
  Console.WriteLine(d.PrettyPrint());
  Console.WriteLine("---------------------------");
 }

A few things to note here:

  • The compiler will allow us to pass a variable declared as dynamic to any method (whatever the type of the parameter that it's expecting), assign it to any variable or cast it to whatever type, but then we'll get the errors at runtime.
  • We already know that Extension Methods are purely a compile time artifact, with all the binding done by the compiler. This means we can't write this:
    dynamic d1;
    d1.GetValue("key");
    cause the dynamic dispatch the ExpandoObject won't take into account my extension methods at all.

When writing this entry I ran into this pretty interesting project, Impromptu Interface. Another interesting idea that I found is thinking about dynamic as a high level type, without a low-level correspondence.