My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, March 26, 2014

What Books Didn't Tell You About ES5 Descriptors - Part 2

Once you've read, Part 3 is out ;-)
In my previous post about descriptors I've left you with a couple of uncommented benchmarks, one comparing Object.defineProperty VS direct property set, and a second one comparing Object.defineProperties VS literal Object notation.
I am sorry to tell you that's still too early to properly comment those benchmarks, and while I am promising you I will tell you how good or bad those look later on, I'd like to put in your face another benchmark, ignoring all powerful daily basis computers are surfing the net, focusing and analyzing "the worst Hardware" I could find these days out there: an old Android 2.x, one of the first FirefoxOS phones, webOS 2 on Palm Pre 2, and a Samsung Omnia 7 with Windows Phone 7.x and IE9 Mobile

About Descriptors And Prototypal Inheritance

If you think that around 1584 classes definitions per second is the problem, and only in the worst Hardware scenario, you should probably have a quick chat with yourself about the architecture you are using for your Software, and what kind of Hardware you are actually targeting.
Just as a gently reminder, this is the Hardware used for the Apollo 11 mission to the Moon:
The Apollo AGC itself is a piece of computing history, it was developed by the MIT Instrumentation Laboratory and it was a quite amazing piece of hardware in the 1960s. It was the first computer to use integrated circuits (ICs), running at 1 Mhz it offered four 16-bit registers, 4K words of RAM and 32K words of ROM. The AGC mutlitasking operating system was called the EXEC, it was capable of executing up to 8 jobs at a time.
Accordingly, ignoring arguments that cannot be proved in the real-world, the rest of the post will be focused on how to use descriptors together with prototypes and "classes".

1st Fact: Zero Performance Impact!

Just to be clear upfront about this topic, using Object.defineProperties(Class.prototype, descriptors) does not affect instances creation performance, in Mobile, as in Desktop browsers.
The rest of this post will rather be about how descriptors work and can be useful so if you are looking for other benchmarks, feel free to come back at Part 3 :P

About Multiple Descriptors Objects

When we use a second argument for Object.create(proto, descriptors) or just the descriptors object through Object.defineProperties(object, descriptors) we are actually performing a classic for/in loop, Douglas Crockford and his JSLint style ... yeah, that one that made your for/in loops slower than they could have been since ever:
// simulating defineProperties
function defineProperties(
  object, descriptors
) {
  for (var key in descriptors) {
    if (descriptors.hasOwnProperty(key)) {
      Object.defineProperty(
        object, key, descriptors[key]);
    }
  }
}
OK, to be fair, this might be optimized in core as Object.keys(object) could be, but still many operations in JavaScript world, native or not, are doomed because of ... guess what? Descriptors were missing, so nobody could define undesired properties as not-enumerable for past 12 years ... do you still think descriptors are such bad news?

The Old ES3 Classes Pattern

One of the most disturbing patterns I keep finding in modern blog posts and even books is the following:
function Person(){}
Person.prototype = {
  constructor: Person,
  // and now ... whatever .. i mean ...
  // DO YOU REALIZE WHAT
  // YOU JUST DID ALREADY ?
};
Since developers are keen to performance and usually most relevant are about CPU rather than RAM usage and/or GC, here a little and quick breakdown of the most broken pattern you've ever seen and used in your own code (I bet so, since I've done that too!)
// defining the class
function Person(){}
Let's start saying that every function has its own prototype object by default, assigned since its creation, and every prototype has a property called constructor which is not enumerable, but configurable and writable as every other thing that comes natively in ES world as already explained in the previous post ... Moreover:
// getting rid for no reason
// to an object that was already there
// and configured as YOU expected!
Person.prototype = {
  // now making `constructor`
  // an **enumerable** property
  constructor: Person
  // now adding more enumerable
  // properties ...
  // CONGRATS !!!
  // YOU NEED hasOwnProperty CHECKS NOW
};
As summary, one developer laziness "to rule them all" ... which explains why we should never actually care about Object.defineProperties performance if all we do in our code is duplicating objects, re-addressing prototypes, and making our own environment unreliable so that a loop without hasOwnProperty check is considered unsafe from our own linter, the tool that supposes to tell us how to write a better code ... how badly screwed is all this?

Descriptors For All The Prototypes!

Instead of throwing away what the language we are using is gently providing to us, we can simply leave things as these are meant to be and enrich them with ease:
function Person(){}
Object.defineProperties(
  // enriching instead of replacing
  Person.prototype,
  {
    // everything we want
    // as Class.prototype
  }
);
If used for all classes, not only we can forget about constructor since, unless specified as descriptor, it will always be the expected one, which is the reason we keep reassigning it in the old ES3 pattern, we don't ask the GC to collect any default prototype object plus the constructor won't be enumerable!

Advantages About Descriptors

Passing through a clean operation as Object.defineProperties is, is not just about preserving the original constructor descriptor and its non-enumerability, it's rather exactly what we want in terms of reliable code, a topic that should never be under estimated in a JS world where many libraries and modules should cooperate together:
function Person(name) {
  this.age = 0;
  this.name = name;
}
Object.defineProperties(
  Person.prototype, {
  grownUp: {
    value: function () {
      return ++this.age;
    }
  }
});

// it's a me!
var me = new Person('andrea');
me.grownUp(); // 1
for(var key in me) {
  console.log(key, me[key]);
}
// age 1
// name andrea
First of all, immutable methods are something actually we've been waiting and asking for and by default, using Object.defineProperties, we have such advantage!
There's no way to reassign by accident grownUp to the me variable, and this is, if you ask me, AWESOME!
For the first time, the meaning of classical OOP makes sense in JavaScript, so that Classes could be defined somehow statically, it's still possible to enrich them later on, but all instances can trust the method they are using.
This has never been even closely similar in ECMAScript 3 era ... do you still think descriptors are such bad news?

Non Writable Properties

Going through all things that are mostly unknown, here the catch: by default all descriptors are not writable, not enumerable, and not configurable, which is actually a good news for Classes, but a not so good for instances and here is why:
function Person(name){
  this.name = name;
}
Object.defineProperties(
  Person.prototype, {
  // assuming we want a default
  // age of 0 per each born person
  age: {
    value: 0
  },
  // same method 
  grownUp: {
    value: function () {
      return ++this.age;
    }
  }
});

var me = new Person('andrea');
me.grownUp(); // 1 (due ++result)
for(var key in me) {
  console.log(key, me[key]);
}
// age 0 <--- !!!
// name andrea
As explained already in Part 1, setting a property to writable:false has a side effect very similar to the following one:
Object.defineProperty(
  Person.prototype,
  'age', {
  get: function () {
    return 0;
  },
  set: function () {
    // only under "use strict" it throws
    if (function(){return !this}()) {
      throw new Error('val is non writable');
    }
  }
});
Above snippet means that any object, inheriting from Person.prototype, will find itself unable to directly define as instance.age = value operation any value because "the invisible setter" will act like a guard, being invoked as we would expect any getter or setter defined in the prototype should!

Getters And Setters

As indeed is demonstrated in every old style benchmark we could find about ES3 prototypal inheritance, methods in the prototype are usually faster than methods defined at runtime.

I am sure you've realized again that's a graph based on the worst case scenario ;-)
Anyway, getters and setters are methods, and as such, these are as slow as any other method inherited through an instance prototype will be ... so don't make a big deal out of them, JS engines are smart enough to speed up in a way methods would be speeded up:
function Rectangle(width, height) {
  this.width = width;
  this.height = height;
}
Object.defineProperties(
  Rectangle.prototype, {
  // returns the generic instance area
  area: {
    get: function () {
      return this.width * this.height;
    }
  }
});

(new Rectangle(3, 3)).area; // 9
(new Rectangle(3, 2)).area; // 6
Once we understand the power and the mechanism behind getters and setters, we can hardly complain about the behavior that writable:false introduced to classes, specially after reading this rationale!

Configurable, If Necessary!

Once again, the simple problem with writable:false is that once inherited, this is not ignored by the syntax:
var a = Object.defineProperty(
  {},
  'lol',
  {value: 'wut'}
);
var b = Object.create(a);
// same as ...
function B(){}
B.prototype = a;

var b = new B;

// so that ...
b.lol = 'ahahahahahahahah';

// ... instead...
b.lol; // 'wut'
So, the bad news is that properties, if specified in a prototype as default values, should always be writable:true, but if these are meant to be specified as immutable, it's always possible to redefine them later on:
function One(){}
Object.defineProperties(
  One.prototype,
  {
    valueOf: {
      value: function () {
        return 1;
      }
    }
  }
);

var badAss = new One;
Object.defineProperty(
  badAss,
  'valueOf',
  {
    value: function () {
      return 2;
    }
  }
);
1 * badAss; // 2

Still Missing

I believe in this post there's a lot of extra material to test against and think about ... but I assure you, the road to mastering ES5 descriptors is still ahead, and a long one, so please come back in few days to see what else you probably didn't know about the current environment your JavaScript is running against ;-)

Monday, March 24, 2014

What Books Didn't Tell You About ES5 Descriptors - Part 1

Once you've read, Part 2 is out ;-)
I've read and reviewed few books these years, and few of them quite recently too; none of them went deep enough on how to use these ES5 features that for long time has been avoided ... reasons?
Somebody might say it's an aesthetics problem: while somebody else might think these offer poor performance: Although I believe is the main reason most developers never ever even investigated about descriptors is that some popular code guide/style written in 2011, the year when ES5 got widely adopted, described new ES5 features as crazy shit: I've already commented that guide in November 2011 and this time I'll try to counter balance that butterfly effect we, as developers and bloggers, should always be aware of when it comes to guidance on programming, right?
Accordingly, the goal of these posts is to tell you everything about ES5 descriptors and also do some myth-busters explaining the what, the why, and the when, about such powerful feature that you'll realize it does not look bad, it's not slow at all if done in a certain way, and it's absolutely not some crazy shit, rather something the moment you'll lear more about you probably wish you already knew and put in production 3 years ago ... ready?

Quick Background on ES5

ES5 has been released under the don't break the web motto. Everything you can do in ES5 can be interpreted in old ES3 browsers without Syntax errors, something not possible, as example, with the incoming ES6 features and syntax changes.
In this scenario, methods like Object.defineProperty where the best place and the best option to not break, syntax speaking, anything around, also leaving developers with the possibility to arbitrary chose to use these methods or not.
Few of them could be easily polyfilled, or at least closely simulated.
Long story short, ES5 today is the most widely adopted ECMAScript Standard, present in every Mobile or Desktop Browser, as well as every server side engine.
The only die-hard browser developers keep want to support is IE8, but we'll see later on that we could use this browser too in order to perform most of the tasks that ES5 introduced.

What Is A Descriptor

Let's consider the following Object:
var object = {
  key: 123
};
The property key can be easily described as enumerable, configurable, and writable, and represented as such through its descriptor:
Object.getOwnPropertyDescriptor(object, 'key');
/*
{
  value:        123,
  writable:     true,
  enumerable:   true,
  configurable: true
}
*/
Above descriptor is the most common one in user land, other common descriptors usually come from native prototypes.
In order to understand how natives are defined in JavaScript, let's have a look on what these properties mean.

enumerable

Properties that are enumerable will always show up in a classic for/in loop, as it would be for the key property in the previous object.
However, all native prototypes are usually defined as such:
Object.getOwnPropertyDescriptor(
  Object.prototype, 'toString'
);
/*
{
  value:        [Function: toString],
  writable:     true,
  enumerable:   false,
  configurable: true
}
*/
Not only new Object won't show inherited methods in a for/in loop, all natives will not show up neither if checked directly:
for(var key in Object.prototype)
  console.log(key); // nothing

Object.keys(Object.prototype); // []

// finally some info!
Object.getOwnPropertyNames(
  Object.prototype);

[
  'constructor',
  'toString',
  'toLocaleString',
  'valueOf',
  'hasOwnProperty',
  'isPrototypeOf',
  'propertyIsEnumerable',
  '__defineGetter__',
  '__lookupGetter__',
  '__defineSetter__',
  '__lookupSetter__',
  '__proto__'
]
Object.getOwnPropertyNames is the only way to retrieve not-enumerable properties from a generic object. This is also something to keep in mind also when we'd like to simply copy own properties from an object to another.
// how to copy all own properties
// **ignoring getters and setters**
Object
  .getOwnPropertyNames(source)
  .forEach(function (key) {
    target[key] = source[key];
  })
;

configurable

When a property is configurable, this means we can re-configure or delete it.
var object = Object.defineProperty(
  {}, 'key', {
    // not enumerable
    // neither writable
    configurable: true,
    value: 123
  }
);

// reconfiguring
Object.defineProperty(
  object, 'key', {
    configurable: true,
    value: 456
  }
);

object.key; // 456

// removing key
delete object.key; // true


// also most native properties and methods
// can be simply dropped as such
delete Object.prototype.__proto__; // true
delete Object.prototype.toString;  // true
If we would like to prevent latest snippet to occur, we can either use Object.seal(Object.prototype), ensuring that all properties cannot be removed but also making impossible to add or remove others, which is as obtrusive as changing it since we don't generally own the Object.prototype, or we could manually loop over all own descriptors and change the configurable part, when necessary, without sealing the whole object:
Object.unconfigurable = (function(){
  function reconfigure(key) {
    var descriptor = Object
      .getOwnPropertyDescriptor(this, key);
    if (descriptor.configurable) {
      descriptor.configurable = false;
      Object.defineProperty(
      this, key, descriptor);
    }
  }
  return function unconfigurable(object) {
    Object
      .getOwnPropertyNames(object)
      .forEach(reconfigure, object)
    ;
  };
}());

// ... later on ...
Object.unconfigurable(
  Object.prototype);

delete Object.prototype.toString; // false
However, this won't guarantee that properties cannot be overwritten, since the writable property of the descriptor, is not affected by Object.seal, neither by above snippet.

writable

While configurable is about the ability to delete or configure a property, writable is about the ability to change its defined value.
var object = {
  key: 123
};

var descriptor = Object
  .getOwnPropertyDescriptor(object, 'key')

// setting as non writable
descriptor.writable = false;
Object.defineProperty(
  object, 'key', descriptor);

// this will fail
object.key = 456;
object.key;  // 123

// remember, writable
// is not about the ability
// to reconfigure it
descriptor.writable = true;
Object.defineProperty(
  object, 'key', descriptor);

object.key = 456;
object.key;  // 456

// neither about the inability
// to remove it
delete object.key; // true
object.key;  // undefined
Generally used to create constant like properties, writable is also the most misleading property when it comes to prototypal inheritance since it creates a trap very similar, conceptually speaking, to the following one:
// concept: similar behavior of
// {writable: false, value: 123}
var a = Object.defineProperty({}, 'val', {
  get: function () {
    return 123;
  },
  set: function () {
    // only under "use strict" it throws
    if (function(){return !this}()) {
      throw new Error('val is non writable');
    }
  }
});
a.val = 456;
a.val; // 123

var b = Object.create(a);
b.val = 456;
b.val; // 123

// it's configurable as own property anyway
Object.defineProperty(
  b, 'val', {value: 456});

b.val; // 456

While this behavior might look very undesired for properties, it ensures that inherited methods cannot be changed at any time anywhere in the prototypal chain which is actually usually the most secure behavior we could ask for.
When a descriptor has writable property, this cannot also contain get or a set one.

get & set

When one of these two is present, the descriptor is consider an accessor one instead of a data one, as it is a writable one which assume also a value which is by default undefined.
configurable and enumerable have exactly same meaning, and here an example of getters:
var arrayLike = Object.defineProperty(
  {}, 'length', {
  get: function () {
    var keys = Object.keys(this);
    return keys.length &&
      Math.max.apply(null, keys) + 1;
  }
});

arrayLike.length; // 0

arrayLike[0] = 1;
arrayLike[1] = 2;
arrayLike.length; // 2
Getters and setters have been around for a while so I won't talk much about what we can do with these two features, just remember that these cannot coexist with writable and value since that won't make sense (we can simply ignore the set to avoid writing or throw, to mimic writable:false behavior and return whatever we want via get to mimic the value)

Are Descriptors Inherited ?

I will cover how to use descriptors through prototypal inheritance and how powerful these are but the simple answer to this topic is: NO, descriptors are never inherited, but whatever behavior is defined in the prototype, as a classic non-enumerable could be, will be reflected regularly through all instances ... not because these will have magically a non enumerable property, simply because the moment their prototype is accessed, this won't show such property as enumerable, same way happens with native Object.prototype as explained at the beginning of this post.

Object Use Cases

Dropping useful cases based on inheritance, here a combination of common use cases per each property descriptor:
  • enumerable is the default choice for all properties defined as literal and it's very useful when debugging in console. An object with non enumerable properties won't reveal itself as good as one with enumerable properties ... as example {a:123} will be shown as such in console while Object.defineProperty({},'a',{value:123}) won't.
  • configurable gives the ability to both delete and redefine a property through a different descriptor. Latter one is less common case but very powerful combined with lazily defined properties.
  • writable, combined with configurable, is the only way we have to define constants like properties. Object.defineProperty(Class, 'CONST', {value: 'immutable'}) is a very nice and safe feature we can use without problems anywhere we want to.
  • get and set are a very transparent way to validate properties or link private methods or variables together. These can also be used as lazy properties, when accessing them should calculate once something expensive, instead of penalizing at runtime through a multitude of similar computations.

Performance

Still removing inheritance related patterns from the equation, these are single property results comparing direct property set VS Object.defineProperty, while these are multiple properties at once via Object.defineProperties VS normal object literal.
It's good to have these bench in, but it's very early to conclude that you should not use these ES5 features ... we are still missing all potentials once descriptors are integrated with prototypal inheritance.
Don't miss the next part of the pot ;)

Tuesday, March 18, 2014

Do Not Require Polyfills

I'll try to keep it as simple as it sound, polyfills should never be a dependency and here is why:

Do Not Confuse Polyfills With Libraries

If you are using any utility library that brings you something similar to requestAnimationFrame under a different namespace that is not the window or the global object, that is not a polyfill but rather a library you have dependencies based on, and this is OK!

Polyfills Do Not Want Maintenance

Indeed, polyfills are scripts usually placed upfront the main application that should be removed when time is right, which means ASAP, without requiring indirectly any update, upgrade, or change from your own module.

Polyfills Aren't Virtually Needed

You don't want to require('latest-browser-or-nodejs'); in your code, because that is pointless, no matter if you use a UMD or a browserify approach, no module should contain a polyfill and here is why:

Global Pollution

Yes, polyfills are usually greedy because being polyfills they fill the environment gap, where the environment is usually not confined in your own closure.

Deadly Obtrusive

If your module defines its logic behind some feature detection and including another module could change this, you are basically dropping an undesired bomb in your system you were not aware of the moment your module acted as it should ... as module, library, whatever it is, that didn't include a bloody obtrusive AMD that changed everything the module knows before that ... I mean, the moment your module is defined, that's the env you expect.

Always Upfront!

Polyfills should have the exclusive position on top of anything you are developing because the day you won't need them you'll simply drop them and everything else will keep working lighter and faster.
Making your polyfill usable as a module won't benefit anything based on it for the simple reason that such modules won't be portable without a potentially not needed/necessary anymore environment normalizer, and need at that time extra maintenance form something assumed to work as that in such environment.

Delegate Dependencies

If your module depends on some polyfill just say so ... any other module that depends on your one might need or rely same polyfill too so don't make such polyfill your own choice .. and once again, if it does not change globally the behavior, it's NOT a polyfill ... in such case, feel free to include it!

What About browserify ?

It's OK to publish modules to npm or bower so that it's possible to create a build task that will include polyfills in the right order, if needed, using require('es5-shim') and require('dom4') and others upfront.
However, if you did the mistake to wrap your polyfill inside an UMD and the define library is around, being the inclusion of modules completely arbitrary in terms of order, you might cause troubles not only for your own logic, but also for all other modules that were expecting, as example, the window.TCPSocket to be there. Fix it dropping any UMD logic around your polyfill, and publish again ;-)

Monday, March 10, 2014

Thank You DHTML Conf

It has been a very unique event I am very happy I've participated as speaker.

It was about a year I wasn't speaking in public and this was the best venue, and surely the most "old school" prepared, I could ask for.

Thanks!

To both organizers, all people there, and other speakers that made me laugh and think at the same time ... quite a lot!

We can really learn from the past of the web, we just need to not forget what is still working and used today, what has never worked and failed already, and what was already possible but we just ignored it.

Here my quick presentation that makes not much sense without me explaining it ... anyway, few things are quite easy to guess ... enjoy :-)

if it's slow or not responsive ... my personal sites are still those cheap solutions I have since quite a while :P