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

Friday, January 18, 2013

Have You Met Empty ?

The proper title for this post could have easily been something like JavaScript Inheritance Demystified or slightly less boring as The Untold Story About JavaScript Objects ...well, thing is, I don't really want to alarm anyone about this story and as a randomly improvised storyteller, let's move forward, and see where it goes, starting from where it all began ...

Elementary, My Dear Watson!

The very first thing we might want to do, in order to make our research, discovery, and piece of programming history useful, is creating a couple of shortcuts that will let us easily analyze the code and the current story:
// retrieve the first inherited prototype
var $proto = Object.getPrototypeOf;

// retrieve all own properties,
// enumerable or not, ES5 stuff !
var $props = Object.getOwnPropertyNames;
Why do we need that? Because almost everything is an instanceof Object in JavaScript world, which simply means, and we'll see this later on, that Object.prototype is inherited all over!

Well, Almost!

Since Object.prototype is an object, there's no way this can be called as a function, right?
No doubts Object inherits at some point its own prototype but who added apply, bind, call, constructor, length, name, and that funny toString behavior in the middle?

Not Function !

That's correct, Function has nothing to do with that. Function actually inherited those properties and redefined some behavior such name and length.
Is the Object constructor instanceof the Function one ? Yes! Is the Function object instanceof Object ? Yes again and trust me: there's no real WTF!
Object instanceof Function; // true
Function instanceof Object; // true

The First Object Ever: null

This is the prototype of the prototypes, if we check $proto(Object.prototype) the result will be null indeed.
As summary, the very number one object to inherit from, possible in fact as Object.create(null) instance too, is this reserved static keyword everybody ever complained about because it returns "object" instead of "null" under typeof null inspection.
Can we start seeing that being the mother and the father of everything we use in JS world, "object" is kinda the best typeof we could possibly expect?

There Are Two Suns!

This is the lie we all believed until now, Object.prototype is where everything inherits from ... well, brace yourself, an hidden Empty object is part of this game!
Chicken or egg, who came first? You cannot use much philosophy in programming, you have to solve stuff and give priority or order to the chaos represented by requirements and/or implementations about specs, right? :D
So here the chain you have always wondered about:
null <
  Object.prototype <
    Empty <
      Function
      Object
Wait a second ... how can Object.prototype then exists before Object is even created ?
So here the secret about JavaScript, the elephant Classic OOP guys keep ignoring in the room: Object.prototype is just an object that's inheriting from null!
The fact we call it Object.prototype is because that's the only way to reach it via JavaScript but here how you could look at the story:
null: the omnipotent entity, the origin of everything,
      the daily Big Bang that expands on each program!

  prototype: like planet Earth,
             the origin of all our user definable problems

    Empty: the supreme emptiness of everything,
           meditation over "dafuq just happened"!

      Function: somebody has to do actually something concrete:
                the slave!

      Object: somebody has to take control of everything:
              the privileged king!
Are we done here? ... uh, wait, I knew that!
"The time has come," the Object said,
"To talk of many things:
Of keys and __proto__ and magic things
Of prototype and kings
And why that Empty is boiling hot
We show that pigs have wings."

The Object.prototype we set!
As prototype itself!
Object.prototype = prototype;


The instanceof Operator

As shortcut, instanceof is freaking fast compared with any user definable interaction with the code.
In few words, if you want to know if ObjA.prototype object is in the prototype chain of objB, you better objB instanceof ObjA rather than ObjA.prototype.isPrototypeOf(objB), I mean .. really, check performance here!

So, once we get the pattern followed by instanceof, it's easy to do the math here:
Object instanceof Object
// means
Object.prototype.isPrototypeOf(Object)
Remember the hierarchy? Object inherits from Empty, and Empty inherits from prototype so, of course Object inherits from prototype, it's transitive!
Object instanceof Function
means
Function.prototype.isPrototypeOf(Object)
Again, Object inherits from Empty so obviously Function.prototype, which is Empty indeed, is one of the prototype of Object ^_^

Who Defined The prototype Behavior?

This is the tricky one ... so, prototype is not even invocable and as such it cannot be used as constructor. Actually, neither can Empty, since it cannot be used as constructor too ... so new Empty will throw, watch out!
In fact, Empty introduces the [[Call]] paradigm, inherited by all primitive constructors such Array, Object, Function, Boolean, but is not inheritable from user defined objects, or better, you need to create a function(){} object to have that special behavior inherited from Empty and the prototype inherited from Function.
Empty.isPrototypeOf(function(){}); // true

Which prototype Behavior ?

Well, this is the main point about instanceof and isPrototypeOf(), the prototype behavior defined in the Function object, the only object adding that prototype property defining its behavior in the program!
$props(Empty)
["apply", "bind", "call", "constructor", "length", "name", "toString"]

$props(Function)
["length", "name", "prototype"]
// could be more in other engines

The Last Troll Ever!

It's clear that Empty introduced the constructor property too and guess what happened there?
"The time has come," the Empty said,
"To talk of many things:
Of constructor and new toString
Of call, bind, apply and kings
And why that caller is boiling hot
We show that pigs have wings."

The Empty.constructor we set!
The Function we just let
So that Function.prototype(aka:Empty).constructor === Function is true :)
Last, but not least, if you think as "Empty function" Empty is fast, just check this bench and realize that it could be the slowest function ever invoked!
So, here is the story of the root of all amazing things we can enjoy on daily basis in this Internet era, could you imagine?

Thursday, January 17, 2013

JS __proto__ Shenanigans

I can't believe it, every time some cool pattern comes into games, __proto__ makes everything pointless, in a trusted meaning of a generic property!

Previously, in Internet Explorer

One of the biggest and most known WTFs in IE is the fact that Object.prototype properties are not enumerable.
While is possible to define such properties in ES5, this is the classic good old IE only scenario we all remember:
for(var key in {toString:"whatever"}) {
  alert(key); // never in IE
}
As simple as that, all native properties in the main prototype were considered {toString:true}.propertyIsEnumerable("toString") === false because indeed, these were not enumerating (just in case: enumerable properties are those that should show up in a for/in loop)

The Same Mistake With __proto__ If Not Worse

That's correct, the moment you play with this property name things start falling a part same old IE way or even worst.
alert(
  {__proto__:"whatever"}.
    propertyIsEnumerable(
      "__proto__"
    ) // this is false !!!
);
Not only enumerability, but also the hasOwnProperty(key) is gone!
var o = {};
o.__proto__ = 123;
o.hasOwnProperty("__proto__");
// false !!!

Do Not Use Such Mistake

Even if part of new specs, __proto__ is showing off all its anti pattern problems we all laughed about when it was IE only.
As a property, we should not have any special case, able of these kind of problems, while we should all keep using Object.statics() function that works internally, rather than on property name level.
So now you know ;)

Monday, January 14, 2013

5 Reasons To Avoid Closure Compiler In Advanced Mode

I believe we all agree that Google Closure Compiler is one of the most advanced tool we have for JavaScript development:
  • fast parsing with pretty printed or minified output with warnings about possible problems or errors
  • type checks analysis before it was cool, as example via java -jar compiler.jar --jscomp_warning=checkTypes --compilation_level=SIMPLE_OPTIMIZATIONS ~/code/file.js
  • creation of source map for an easier debugging experience with the real, minified, code
  • best raw compression ratio, death code elimination, and more with @compilation_level ADVANCED_OPTIMIZATIONS
I also believe the latter point is a trap for developers and projects: unable to scale and capable of many headaches and shenanigans.
If you want to know why, here a list of the top 5 facts I always talk about, when some developer comes to me telling the solution to all problems is advanced optimizations.

1. Incompatible With ES5

Every current version of a browser is compatible with ES5 features but the tool that supposes to help us is able to change the program creating security problems or misbehaving logic in our code.

No "use strict";

this is the very first problem. Not much about with() statement and eval(), rather about the possibility to pollute by mistake the global scope so that any namespace could be destroyed by accident.
function setName(name) {
  "use strict";
  this.name = name;
}

var obj = {setName: setName};
obj.setName("name");
Above code will produce the warning dangerous use of the global this object at line 7 character 0: this.name = name; which is correct only because
  1. it does not understand how the function is used
  2. the "use strict"; directive has been removed
If you think that's OK you have no idea how many libraries out there might use the window.name property, the one that never changes in a tab lifecycle, you should think that name could have been any runtime or predefined property used by your library or any dependency your library has. ... is this not enough? Let's see more then :)

Update on "use strict";

As @slicknet pointed out, there is the possibility to support the "use strict" directive via --language=ECMASCRIPT5_STRICT command line argument.
This flag comes in any case with extra related bugs.
However, I didn't know that flag and this is cool but "use strict"; in JavaScript world is already a directive so that shuold not be necessary at all. We are in an era where ES3 only browsers are a minority and tools should be updated accordingly, IMHO.
This part is another reason modules are not friendly with Closure Compiler Advanced portability and security is still under attack. Please read more!

Object.defineProperty(shenanigans)

Since strings are the only thing that cannot be changed, guess what is the output here:
var program = Object.defineProperty(
  {},
  "theUntouchablePropertyName",
  {
    writable: true,
    configurable: true,
    enumerable: true,
    value: 123
  }
);
alert(program.theUntouchablePropertyName);
You can test almost all these snippets via the Closure Compiler Service to double check, if you want. Anyway, here what that will be:
var a=Object.defineProperty({},
"theUntouchablePropertyName",
// **STATIC WHITE LIST**
{writable:!0,configurable:!0,enumerable:!0,value:123});
alert(a.a); // <== You see this ?
If you are thinking "sure, you have to access that property as program["theUntouchablePropertyName"]" bear with me 'cause I am getting there ...
The number of problems we have with above snippet are different. The very first one is that with a massive usage of inline ES5 descriptors there's no final size gain because of the static list of properties that Closure Compiler won't change.
All DOM classes and properties cannot be touched, together with events properties and basically everything defined in the W3C together with all globals and non standard features such window.opera which is preserved and I have no idea what else but the elephant here is that prefixed properties are not supported too!
function doAmazingStuff(obj) {
  if (obj.type === "custom:event") {
    obj.target.onwebkitTransitionEnd();
  }
}

doAmazingStuff({});
Above snippet will result in this one:
var a={};"custom:event"===a.type&&a.target.a();

Why This Is A Problem

You might say that, as everything else, the property should be accessed dynamically. But how comes that properties such writable and enumerable are maintained while anything that could come from ES6 or most recent proposal might be not supported and so compromised? What if some browser has some special case that Closure Compiler is not aware of in a reality where every browser might have some special case in core?
Are we really willing to write an inconsistently looking code such
var descriptor = {
  configurable: true,
  "inheritable": false
};
to avoid problems? Uh wait ... I know where you come from ...

2. Requires A Different Syntax

When I've tweeted about another-js somebody complained about the fact that developers will get really bored to obj.get("key") and obj.set("key", value) all the time ... and yes, I might agree that is much more typing for large applications. While the project is about the ability to observe everything that's going on, is not required at all to follow that convention: when we know an object should not be observable, we can access properties directly in order to get or set values as we have always done.
In Closure Compiler Advanced world we are forced to follow a convention about accessing properties which is dynamically rather than statically.
// JavaScript
obj.newProp = obj.oldProp + 123;

// Closure Compiler Advanced (CCA)
obj["newProp"] = obj["oldProp"] + 123;
Holy crap, I have spent already at least twice the time to write the second line ... and this is because I am planning to make this old function still able to work:
function doMoarWithDescriptors(d) {
  for (var key in d) {
    if (k === "newProp") {
      // would never happen after CCA
      // if not changing the code
    }
  }
}
So, not only we need to type more with less ability to be helped by autoComplete, since strings are strings and not every IDE supports dynamic access, but every time we would like to be sure that a key is the one we expect, in a state machine, or a more common switch(), we need to do refactoring with all consequences we know about refactoring in big, as well as smaller projects!
... and the best part is ...

3. More Things To Be Worried About

The funnies non-sense about Closure Compiler Advanced, is that while everyone is trying to change JavaScript because they believe is not good as it is and it has too many quirks in the specifications, Closure Compiler Advanced adds even more syntax problems to be worried about .. isn't this lovely insane?

Danger Indeed !

The unique id used to described problems caused by the Closure Compiler Advanced is #danger, because disasters might happen to everything if you don't follow those rules ... but wait a minute ... shouldn't DEV tools help rather than create more problems to be aware of ? Ask yourself ... you are probably still struggling understanding JavaScript coercion but you had to learn that obj["prop"] is a better way to access a property ... you know what I mean, right?
Even worst, something described in that solution list is the most common use case in modern JavaScript and guess what ...

4. It Does Not Scale With RequireJS/AMD Modules

True story bro, and reasons are many!

Requires Extra Steps In The Loop

This is not a big deal, but you must be able to create code that can be put together and then split again a part. While this might sound easy, the ability to eliminate death code and understand the code in a way that closures, namespaces, and about everything could be inlined, might be a problem. How do you understand what piece of code can be split and still work as it was before and for sure? There's no way you can run unit tests to prove that part is still working unless you compile all tests together and be able to split them a part. How much extra effort and possible trouble maker variables in the middle for a flow that should be as linear and easy as possible?

Broken Source Map

That's correct, is not only about splitting back the code when you want preserve a lazy module loading approach, the source map, the coolest feature ever, won't mach a thing anymore because it will be generated in the whole block of all modules and not for the single one so rows and columns will be screwed ^_^

Worse Performance

In order to export a module and make it compatible with Closure Compiler Advanced after build, which could be the case if you don't want to put the module source online or you upload in a CDN only its already minified version, either you create the exports.js version of the file, which means you are assuming every user is basing the build process on Closure Compiler, or you need to manually fix the exports so that methods and properties won't be changed.
// original module for CCA
module["exports"] = {
  "dontTouchThis": genericValue
};
If you are the one using Closure Compiler to create your own script, and you use Advanced Optimizations, above code will result in module.exports={dontTouchThis:genericValue};
Cool, uh? The only problem is that if you pass again that code through the Closure Compiler you are screwed because the result will be module.a={b:genericValue};.
Accordingly, you have to change back the property that should never be touched resulting in a minified version that is module["exports"]={"dontTouchThis":genericValue};
Not every browser optimizes runtime that kind of property access as Chrome does, you can see specially mobile, IE, and others going 3X or more faster with direct property rather than squared brackets plus string access. I know, this could be optimized by browsers but ... 'till now, is not, and I don't really want to write two kind of ways to access properties all the time.

5. A Compromised Security

An automation is an automation and the current status of software AI is far away from perfect or superior, period.
This means that sentences like Crockford's one about JSLint, regardless the excellent interview, should be taken metaphorically speaking and nothing more:
JSLint is smarter than I am at JavaScript and it is probably smarter than you, too. So as painful as it is: Follow its advice. It is trying to help you.
If you think the same about Closure Compiler in Advanced mode here the easy answer:



This tool has one task to do and is not to understand the code in a way developers do.
As example, if you want to avoid that your whole namespace is removed by mistake in the global scope and you don't have ES5 possibilities, as broken as these are in Closure Compiler world, you will certainly declare your namespace as:
// if already defined in the global scope,
// do not redefine it!
// handy for libraries required in different
// other libraries
var myNamespace = myNamespace || {
  utility: {
    // the magic
  }
};
As you know, var defined variables cannot be deleted.
delete myNamespace;
delete window.myNamespace;
delete this.myNamespace;
// it doesn't matter
typeof myNamespace; // "object" !!!
This is because there's no way that by accident someone can delete that namespace ... how? Here an example:
// let's pretend this is a global utility
window["clearProperties"] = function () {
  var self = this;
  for(var key in self) {
    delete self[key];
  }
};
This will compile into next snippet, and right now without warnings:
window.clearProperties=function(){for(var a in this)delete this[a]};
Right ... I have to tell you something ... first of all:

That Is A Bug

Being a software, Closure Compiler can have bugs as any other software you are creating or you know.
Since, as I have said, is not really smarter than us, Closure Compiler created in this case a piece of code that if you pass it again to the closure compiler itself will throw errors all over the place.
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 1 character 59
window.clearProperties=function(){for(var a in this)delete this[a]};
In case you are wondering what the initial bug is, using next piece of code without var self = this; upfront causes warnings:
window["clearProperties"] = function () {
  // GCC not that smart here
  // it does not understand addressed `this`
  // warnings only in this case
  for(var key in this) {
    delete this[key];
  }
};
So, let me recap: Closure Compiler generates code you should not write ... got it?
That's how much is worth an advice from any automatically transformed, and meant code ...

That Namespace Can Be Deleted

So here was my main point: you don't want to make the namespace deletable but if you write just the very first snippet with a variable declaration, the output will be most likely this one:
Your code compiled to down to 0 bytes!
And no warnings at all ... great ... so how about another boring syntax change to learn such:
var myNamespace =
  window.myNamespace =
  myNamespace ||
  {
    utility: {
      // the magic
    }
  }
;
No way, that crap compiles to var b=window.a=b||{b:{}}; and with one warning, which means we have to double check the warning to be sure is safe, plus we have a double global namespace pollution with both a and b ... awesome ... now ask yourself: should I waste my time investigating about Closure Compiler Advanced problems, rather than focus on software development?

Closure Advanced Is Just Bad

I don't know why the advanced optimization option became so popular but I've personally never used it and never suggested it.
The amount of extra crap caused by this obtrusive directive you don't even want to think about is massive!

Myths About Size

One reason I've been thinking about is that somebody said that this option is able to make miracles within the code. A part that I've never considered a broken environment a worthy miracle, if that is about the elimination of death code so that even if you want to hook in runtime you are screwed ... well, enjoy!
However, that code is 90% of the time there for a reason and if you have like 30% of code that should not be there once minified, ask yourself why you are using closure compiler rather than clean up your bloody messed up and pointless code: profit!

The Size That Should Matter

Let's be realistic ... if you have 1Mb of JavaScript the problem is not in those few bytes you could save minifying properties. You are also probably not considering that these two snippets are equivalent:
// how you write for CCA
window["namespace"] = {
  "dontChangeSinceExported": {}
};

// how is JS
var namespace = {
  dontChangeSinceExported: {}
};
The funny part is that after minification the second, normal, natural, fully JS approach, wins!
// after CCA
window.namespace={dontChangeSinceExported:{}};

// after SIMPLE_OPTIMIZATION
var namespace={dontChangeSinceExported:{}};
3 bytes less and a safer namespace ... hell yeah!!!

As Summary

Closure Compiler is really the best tool I know for many reasons, included the ability to create warnings if you don't respect the Java Docs Like Annotation but the ADVANCED_OPTIMIZATION flag has so many problems that I wonder if is really worth it for you to adopt it. A simply minified code with a minifier able to generate source map, understand type checks, and let your logic, as developer, be always available, is a full of win that together with gzip compression will never be the **real** bottleneck.
Death code elimination is a good hint for a tool, not for a minifier able to screw up logic and code. I'd love to see death code elimination tools detached from the minification logic or upfront with the ability to understand what is really death code and drop it, rather than letting an automation understand that was OK to do.
My 2 cents

A Tiny Update

One thing I have forgotten to mention, is that AFAIK Closure Compiler Advanced supports by default Java Documentation, but this is not capable to even tell us inside the generated html whenever a property should be accessed as exported, via obj["property"], or a mungable one, as obj.property could be.

Saturday, January 12, 2013

A Simplified Universal Module Definition

There are several UMD ways to define a module with zero dependencies but I believe that's quite an overhead so here an alternative:
// please read next example too
// which seems to be better for AMD tools
(this.define || Object)(
  this.exportName = exportValue
);
Update with a nice hint by @kentaromiura where the other side of define could be just a function and not a new function as initially proposed.
Another update suggested by @unscriptable that should not break AMD tools, neither CommonJS, neither global Rhino or window, still leaking a couple of properties that should be reserved for module stuff anyhow.
var
  define = define || Object,
  exports = this.exports || this // *
;
define(
  exports.module = {}
);
Nice one, and if you are wondering why this.exports is needed, is because RingoJS apparently does not follow a de-facto standard as this as module exports is for other CommonJS implementations.

Even Better

If you don't want to pollute the scope at all:
(this.define || Object)(
  (this.exports || this).module = {}
);
now all patterns in one for easy portability, cool?

What Is `this`

In node, this is always the exports object, if the module has been loaded through require, so this.name = value is not different from exports.name = value.
Outside node.js world, this will be the global object or any augmented environment or namespace if the file is loaded as text and evaluated a part.
This makes automatically the module mock ready.

Less Fairytales, Please

This trend to double check that define function has a truthy amd is hilarious. The whole purpose of going modules is to avoid global object pollution so, if you have in your code any script that create an insignificant define variable, function, or property, in the global scope, drop that jurassic script or rename that function in that script instead of check that property all over.
Also, please consider that a property could be part of any object so that check gives us nothing ... right? (but I wouldn't name a propety `amd` ... sure, as well as I wouldn't name a global function define ...)

A Basic Example

// what.js
(this.define || function(){})(
this.what = {
  ever: function () {
    console.log("Hello");
  }
});

// node.js
var what = require('./what.js').what;
what.ever(); // Hello

// browser
<script src="what.js"></script>
<script>
what.ever(); // Hello
</script>

// AMD
require('what.js', function (what) {
  what.ever(); // Hello
});
All this works with closures too, if necessary, so you don't pollute the global scope in non node environment.
(this.define || function(){})(
this.what = function(){
  var Hello = "Hello";
  return {
    ever: function () {
      console.log(Hello);
    }
  };
}(/* **INSTANTLY INVOKED** */));
As summary, if you want to create a tiny library, utility, module, and you don't have/want dependencies, this approach has a minimum overhead of 39 bytes without compression vs 158. Now multiply this per each file you have there and also try to remember my suggested approach, I bet you have it already ... now tell me the other with if/elses :P

But ... Global Scope Polluted With Define ?

I believe this is another fairytale. If you understand how AMD works you realize the moment you execute code in the closure the module is loaded correctly and passed as argument which means, basically, who cares what that argument outside that scope.
Said that, when it comes for globals name clashes possibilities are really low. The classic $ function or the _ one are two example but again, if you use AMD you receive the right argument while if you don't use AMD and you just inject script you do want that property in the global scope and again, if you don't use a module loader, it's your problem if you have both underscore and lodash in your global scope. Just drop one of them ... and enjoy this simplified UMD :)

Sunday, January 06, 2013

The Power Of Getters

While examples used in this post are implemented in JavaScript, concepts discussed here about getters are, in my experience, universally valid.
No matter if we are programming client or server, getters can be full of wins and if you think getters are a bad practice because of performance keep reading and you might realize getters are a good practice for performance too.
As summary, this entry is about getters and few patterns you might not know or ever thought about but yeah, is a long one so ... grab a coffee, open a console if you want to test some snippet and enjoy!
Update
JavaScript allows inline runtime overload of inherited getters so that properties can be redefined as such, when and if necessary.
This is not possible, or not so easy, with Java or other classical OOP languages.
This update is for those thinking this topic has been already discussed somewhere else and there's nothing more to learn about ... well, they might be wrong! ;)

What

Generally speaking, a getter is a method invoked behind the scene and transparently. It does not require arguments and it looks exactly as any other property.
Historically represented as __defineGetter__ Object method in older browsers (but IE), ES5 allows us to use a more elegant and powerful Object.defineProperty method while older IE could use, when and if necessary, VBScript madness. However, consider that today all mobile and desktop browsers support getters, as well as server side JS implementations as showed in this table. Here the most basic getter example:
var o = Object.defineProperty(
  {},    // a generic object
  "key", // a generic property name
  // the method invoked every time
  {get: function () {
    console.log('it works!');
    return 123;
  }}
);

// will log 'it works!'
o.key; // 123

// this will throw an error
o.key();
// getters are not methods!
I know, pretty boring so far and nothing new so ... let's move on!

Why

Getters are usually behind special behaviors such read-only non-constant properties, as HTMLElement#firstChild could be, or (reaction|mutation)able properties such Array#length.
// DOM
document
  .body
  // equivalent of
  // function () {
  //   return document
  //     .getElementsByTagName(
  //       "body"
  //      )[0];
  // }
  .firstChild
  // equivalent of
  // function () {
  //   return this
  //     .getElementsByTagName(
  //       "*"
  //      )[0];
  // }
;

// Array#length
var a = [1, 2, 3];
a.length; // getter: 3
a.length = 1; // setter
a; // [1]
a.length; // getter: 1

A First Look At Performance

If we perform every time an expensive operation as the one described to obtain the body, of course performance cannot be that good. Thing is, the engine might perform that every time because it must be reliable when we ask again for the body, being this just a node inside the documentElement that can be replaced as any other node at any time.
However, even the engine could be optimized when it comes to widely used accessors as firstChild could be, and this is what we can do as well with our defined getters ( and if you are wondering how to speed up the document.body access, well ... just use var body = document.body; on top of your closure if you are sure no other script will ever replace that node which is 99% of use cases, I guess ... drop that script otherwise :D )

A DOM Element Example

Use cases for getters are many but for the sake of explaining this topic, I have chosen a classic DOM simulation example. Here the very basic constructor:
// A basic DOM Element
function Element() {
  this.children = [];
}
That is quite common constructor for many other use cases too, right? What if I tell you that there is already something inefficient in that simple constructor?

Already Better With Getters

So here the thing, when we create an object, this might have many properties that could be objects or arrays or any sort of instance, isn't it? Now question yourself: am I going to use all those objects by default or instantly?
I believe the answer will be most of the time: NO!
function Element() {}
// lazy boosted getter
Object.defineProperty(
  // per each instance
  Element.prototype,
  // when children property is accessed
  "children", {
  get: function () {
    // redefine it with the array
    // dropping the inherited getter
    return Object.defineProperty(
      // and setting it as own property
      this, "children", {value: []}
    ).children;
  }
});

// example
var el = new Element;
// later on, when/if necessary
el.children.push(otherElement);
We can see above benchmark results here. In real world the boost we have per each instance creation, and the lazy initialization of many object properties, will make the benchmark even more meaningful.
Moreover, what jsperf never shows is the lower amount of used RAM adopting this pattern based on getters. It is true that we have a bigger overhead in the code itself, but unless every instance will use those properties, the number of objects to handle will be reduced N times per instance creation and this is a win for Garbage Collector operations too.

Recycling The Pattern

OK, that looks a lot of overhead for such common pattern, when it comes to properties as objects, so how could we reuse that pattern? Here an example:
function defineLazyAccessor(
  proto,        // the generic prototype
  name,         // the generic property name
  getNewValue,  // the callback that returns the value
  notEnumerable // optional non-enumerability
) {
  var descriptor = Object.create(null);
  descriptor.enumerable = !notEnumerable;
  Object.defineProperty(Element.prototype, name, {
    enumerable: !notEnumerable,
    get: function () {
      descriptor.value = getNewValue();
      return Object.defineProperty(
        this, name, descriptor
      )[name];
    }
  });
}

// so that we can obtain the same via
defineLazyAccessor(
  Element.prototype,
  "children",
  // the new value per each instance
  function () {
    return [];
  }
);
The callable value is a compromise for raw performance but worth it. An extra call per each property and once should never be a problem while RAM, GC operations, and initialization per each instance, specially when many instances are created, coul dbe quite a bottleneck.
Now, back to the main constructor :)

The Element Behavior

For this post sake we would like to simulate appendChild(childNode) and firstChild as well as lastChild. Theoretically the method itself could be the best place to obtain this behavior, something like this:
Element.prototype.appendChild = function (el) {
  this.children.push(el);
  this.firstChild = this.children[0];
  // to make the code meaningful with the logic
  // implemented later on ... this is:
  this.lastChild = this.children[
    this.children.length - 1
  ];
  // instead of this.lastChild = el;
  return el;
};
Above snippet is compared with another one we'll see later on in this benchmark.

Faster But Unreliable

Yes, it is faster, but what happens if someone will use another method such replaceChild() passing, as example, a document fragment so that the number of children could change? And what if the other method changes the firstChild or the lastChild?
In few words, inline properties assignment are not an option in this case so, let's try to understand what should we do in order to obtain those properties and clean them up easily with other methods.

An Improved defineLazyAccessor()

If we want to be able to reconfigure a property or reuse the inherited getter, the function we have seen before needs some change:
var defineLazyAccessor = function() {
  var
    O = Object,
    defineProperty = O.defineProperty,
    // be sure no properties can be inherited
    // reused descriptor for prototypes
    dProto = O.create(null),
    // reused descriptor for properties
    dThis = O.create(null)
  ;
  // must be able to be removed
  dThis.configurable = true;
  return function defineLazyAccessor(
    proto, name, getNewValue, notEnumerable
  ) {
    dProto.enumerable = !notEnumerable;
    dProto.get = function () {
      dThis.enumerable = !notEnumerable;
      dThis.value = getNewValue.call(this);
      return defineProperty(this, name, dThis)[name];
    };
    defineProperty(proto, name, dProto);
  };
}();
At this point we are able to define firstChild or lastChild and remove them any time we appendChild()
// firstChild
defineLazyAccessor(
  Element.prototype,
  "firstChild",
  function () {
    return this.children[0];
  }
);

// lastChild
defineLazyAccessor(
  Element.prototype,
  "lastChild",
  function () {
    return this.children[
      this.children.length - 1
    ];
  }
);

// the method to appendChild
Element.prototype.appendChild = function(el) {
  // these properties might be different
  // if these were not defined or no children
  // were present
  delete this.firstChild;
  // and surely the last one is different
  // after we push the element
  delete this.lastChild;

  // current logic for this method
  this.children.push(el);
  return el;
};

Optimize ... But What?

It is really important to understand what we are trying to optimize here which is not the appendChild(el) method but firstChild and lastChild repeated access, assuming every single method will use somehow these properties as well as the rest of the surrounding code.
Accordingly, we want to be sure that these are dynamic but also assigned once and never again until some change is performed. This benchmark shows performance gap between always getter and current, suggested, optimization. It must be said that V8 does an excellent work optimizing repeated getters, but also we need to consider that daily code is, I believe, much more complex than what I am showing/doing here.

Avoid Boring Patterns

The repeated delete thingy is already annoying and we have only two properties. An easy utility could be this one:
function cleanUp(self) {
  for(var
    // could be created somewhere else once
    name = [
      "lastChild",
      "firstChild" // and so on
    ],
    i = name.length; i--;
    delete self[name[i]]
  );
  return self;
}
We could use above function in this way:
Element.prototype.appendChild = function(el) {
  cleanUp(this).children.push(el);
  return el;
};

Still Boring ...

We could also automate the creation of the cleanUp() function, making simpler also the definition of all these lazy accessors. So, how about this?
function defineLazyAccessors(proto, descriptors) {
  for (var
    key, curr, length,
    keys = Object.keys(descriptors),
    i = 0; i < keys.length;
  ) {
    curr = descriptors[
      key = keys[i++]
    ];
    defineLazyAccessor(
      proto,
      key,
      curr.get,
      !curr.enumerable
    );
    if (curr.preserve) keys.splice(--i, 1);
  }
  length = keys.length;
  return function cleanUp(self) {
    self || (self = this);
    for(i = 0; i < length; delete self[keys[i++]]);
    return self;
  }
}

var cleanUp = defineLazyAccessors(
  Element.prototype, {
  children: {
    preserve: true,
    enumerable: true,
    get: function () {
      return [];
    }
  },
  firstChild: {
    get: function () {
      return this.children[0];
    }
  },
  lastChild: {
    get: function() {
      return this.children[
        this.children.length - 1
      ];
    }
  }
});

Benchmark All Together

OK, it's time to test what we have optimized until now. The test would like to simulate an environment where most common operations are Element instances creation and firstChild and lastChild access:
function benchIt(Element) {
  // 200 instances
  for (var i = 0; i < 200; i++) {
    var el = new Element;
    // 5 appendChild of new Element per instance
    for (var j = 0; j < 5; j++) {
      el.appendChild(new Element);
    }
    // 100 firstChild and lastChild access
    for (j = 0; j < 100; j++) {
      result = el.firstChild && el.lastChild;
    }
  }
}
For some reason, and I believe it's a sort of false positive due benchmark nature, Chrome is able to optimize those repeated getters more than expected. It is, however, the only one faster in this bench but this is kinda irrelevant, if you understood the point of this post ... let's summarize it!

Getters Are Powerful Because

  • can be inherited, and manipulated to improve performance when and if necessary
  • can help complex objects to initialize one or more heavy property later on, and only if necessary
  • could be tracked in an easier way, simply adding a notification mechanism per each time the getter is accessed
  • APIs look cleaner and transparent for their users
Enough said? Your comments are welcome :)

Friday, December 28, 2012

A Cross Platform Inherit Function

This (apparently non working) gist gave me the hint. Stuff I've been dealing with for a while, finally used to bring an Object.create(firstArgOnly) cross platform/engine/client/server code that works. The name? inherit()

More Reliable Than Object.create()

The reason I didn't even try to polyfill the ES5 Object.create() method is quite easy: it is not possible to shim it in a cross platform way due second argument which requires descriptors features, highly improbable to simulate properly. Even if browsers support the create() method, inherit() guarantee that no second argument will ever be used so we are safe from inconsistencies within the function.

Forget hasOwnProperty !

Yeah, one of the coolest things about being able to inherit from null is the fact not even Object.prototype is inherited so we can create real empty objects without worrying about surrounding environment, 3rd parts obtrusive libraries, and the boring and slow obj.hasOwnProperty(key) check.
// some obtrusive code
Object.prototype.troll = function (up) {
  throw up;
};

// empty object in every browser/env
var dict = inherit(null);
dict.anyKey = anyValue;

// later on ...
for (var key in dict) {
  // only 'anyKey'
}
That's correct, objects that inherit from null are not affected by the Object.prototype ... really, we cannot even print them without defining a toString method!

Update: On IE DontEnum Bug

Unfortunately the fact IE does not enumerate toString and other native Object.prototype names is not solved here for the simple reason here we are not solving that problem, here we are solving inheritance. However,I think is a must know that even objects created via this function needs an extra loop or something like this:

Not Only Null

This function should just work with anything we might need to inherit and we can also inherit from inheriting objects without problems. Consider this an end of the year tiny present just to remind some basic concept about JS that is still valid: Objects inherit from Objects and that's pretty much it :) Enjoy and see you next year!

Wednesday, November 28, 2012

My Name Is Bound, Method Bound ...

it seems to me the most obvious thing ever but I keep finding here and there these common anti pattern:
// 1. The timer Case
this.timer = setTimeout(
  this.doStuff.bind(this), 500
);

// 2. The Listener Case
(objOrEl || this).addEventListener(
  type, this.method.bind(this), false
);

What Is Wrong

I have explained a while ago what's wrong and how to improve these cases but I understand the code was too scary and the post was too long so here the summary:
  1. every setTimeout() call will create a new bound object and this is both redundant and inefficient plus it's not GC friendly
  2. there is no way to retrieve that listener created inline so it's impossible to remove the listener any time is necessary ... yes, even after, when you do refactoring 'cause you will need to clean up listeners

What You Need

The short version is less than a tweet, 64bytes: function b(o,s,t){return(t=this)[s="@"+o]||(t[s]=t[o].bind(t))} This is the equivalent of:
// as generic prototype method
function bound(methodName) {
  var boundName = "__bound__" + methodName;
  return this[boundName] || (
    this[boundName] = this[methodName].bind(this)
  );
}

// as generic utility
function bound(object, methodName) {
  var boundName = "__bound__" + methodName;
  return object[boundName] || (
    object[boundName] = object[methodName].bind(object)
  );
}

// as stand alone dependencies free prototype method
var bound = function(){
  function bound(methodName) {
    var boundName = uniqueId + methodName;
    return this[boundName] || (
      this[boundName] = bind.call(this[methodName], this)
    );
  }
  var
    uniqueId = "__bound__", // + Math.random(),
    bind = bound.bind || function bind(self) {
      var callback = this;
      return function bound() {
        return callback.apply(self, arguments);
      };
    }
  ;
  return bound;
}();

// really ... you can write
// this little thing in many ways

Pick One And Use It !

These are benefits over the simple, ultra fast, performance oriented, and memory safe approach:
// 1. The timer Case
this.timer = setTimeout(
  this.bound("doStuff"), 500
);

// 2. The Listener Case
(objOrEl || this).addEventListener(
  type, this.bound("method"), false
);
  1. every setTimeout() call, if any, will create one single bound object
  2. you can remove the listener at any time through the same call, i.e. (objOrEl || this).removeEventListener(type, this.bound("method"), false);

Is That It ?

You are free to over complicate this concept as much as you want as long as you got the point: there's no need to create a new bound Object per each call plus your life will be much easier following this pattern focusing on logic rather than possible typos, boring variable assignments, etc etc ... this works and it's what you need and what you want now. I'm also moving my hands as a Jedi so I hope I've convinced you!

Saturday, November 03, 2012

Some Common Web Nonsense

Many times I read or write silly stuff and often it takes a while before I realize "what dafuq did I just read ?" Well, this post is about just few a-ha moments, together with WTFs, I keep having from time to time: enjoy!

Those 4 Repeated + Disturbing Bytes

I mean, this must come first, right? Web Development Tools are improving like hell and Web App development are 99% of the time behind a build process able to shrink HTML, recompile and optimize CSS, eliminate even death code from JS after parsing, recompilation, minification, pre-gzip-compression ... you name it ... and finally, we gonna have the output with a file called: mystuff.min.js ?!?! Am I the only one thinking that this does not make sense and all files should be named by default .max so that the equivalent after minifcation won't include those damn 4 bytes per each file? Entire CDN dedicated to common libraries and these expose minified files with .min extension ... isn't this bloody brilliant?

The "Not So Smart" Condition

This time is about logic, and the fact that order matters. "Which order?" you say? Thanks for asking!
// knowing only one stuff item has a value
for (var fValue, i = 0; i < stuff.length; i++) {
  fValue = parseFloat(computate(stuff[i])) ||
           fValue;
}
Above code might look weird but it's actually more common than we can imagine. Think about defining, as example, a prefixed method so that only one of them will be available. As soon as the value is not undefined we keep going checking for no reason something we don't need so ... can you spot the difference?
// knowing only one stuff item has a value
for (var fValue, i = 0; i < stuff.length; i++) {
  fValue || (
    fValue = parseFloat(computate(stuff[i]))
  );
}
If fValue has a value there is no reason to perform other expensive function calls. Moreover, how can we be that lazy that breaking a for loop is one of those things I basically never see in production code ?
// knowing only one stuff item has a value
for (var fValue, i = 0; i < stuff.length; i++) {
  if (fValue = parseFloat(
    computate(stuff[i]))
  ) break;
}
Scary ... uh ? Point here is: always think about the execution order, logic, cost of your boolean expressions ... you might realize swapping few things around could result in better performance easily while adding a break, sometimes, will be smarter than anything else.

Not Just Missing The Falsy

This is the most common one, no way JS developers will learn this differently. I have tried many times but there's nothing to do, bad habits are bad habits! Let's see what I am talking about ...
obj.prop = obj.prop || defProp;
Can anyone answer exactly what are we trying to do up there? ^_^ Don't bother, here the summary and ... NO, we are not trying to do what we think!
  1. access a possibly undefined property to a generic object
  2. if that was a getter, invoking a getter of that object
  3. either getter or property, verifying after lookup that value is not "", 0, false, NaN, null, or undefined
  4. even if defined, discarding any of previous valid values in order to lookup for the variable defProp, assuming this won't have similar values we already discarded or the sequence could be infinitely pointless if repeated
  5. once a value has been addressed, if any, assign as the property of the object
  6. if this has a setter, invoke the setter for no reason potentially reacting for no reason as property update.
  7. if the prop had a getter only, we have simply raised an Error ^_^ and without any valid reason

Nobody Uses Getters/Setters Anyhow

Excuse me? It's even worst than we think since one of the most powerful, cool, useful, tools ever for JS has been approved in harmony: Object.observe(). Can you imagine a defProp as NaN by mistake so that these three lines will most likely cause three records notifications because we are using a dumb pattern to assign a property if not defined yet? ^_^
// NaN != NaN => true
var defProp = NaN;
obj.prop = obj.prop || defProp;
obj.prop = obj.prop || defProp;
obj.prop = obj.prop || defProp;
// 3 notification records
// 1 as "new", the one we are interested
// 2 as update, with "same value" ...
Just Brilliant, and moArover this habit is so common that whoever will decide to simulate Object.observe() through Proxy (I am already, stay tuned) will need to guard the Records creations and notifications avoiding redundant notification because developers keep reassigning for no reason!

As Easy As This

// the in operator does not trigger anything
"prop" in obj || (
  obj.pro = defProp
);

// alternatively, no trigging
obj.hasOwnProperty("prop") || (
  obj.prop = defProp
);
There, you better embrace this pattern or you gonna have bad time soon either with Proxy, already available, and Object.observe, specially when we don't know who created the object and how. So, once again, repeat with me: avoid property access and/or reassignment for no reason, no excuse!

Bitwise To The Rescue

Rather than understand them, we often avoid them ... well, we shouldn't. Bitwise are cool and let us make a lot of things. These days we are discussing Collection#has(key) and Collection#contains(value) where latter one could be the equivalent, if it won't use identicalType() to -1 < arr.indexOf(value) or, as I can read in many source code, the boring arr.indexOf(value) !== -1. How about if (~arr.indexOf(value)) { ... } to know if an Array contains a value? Problems only with massive collection length but that's 99% of the time not our case. If you are wondering what's going on there, consider that ~ is the equivalent operation of -(x + 1) where -1 is the only number that becomes 0, the falsy value, while all other indexes, included 0, will be -1 or lower number, all truthy.

Smart Configuration

How many times we end up defining configuration options as strings ? ie, "shrink", "minify", "lint" ... And how many check to define one or more behavior, accordingly to these strings? And how about having same behavior within different configuration options ? if (obj.option == "shrink" || obj.option == "minify") { ... } or even this: /^shrink|minify$/.test(obj.option), creating a RegExp object maybe for each time we want to check that option ... how about this:
var Option = {};
Option.SHRINK = 1 << 0; // pow(2, 0)
Option.MINIFY = 1 << 1; // pow(2, 1)
Option.LINT   = 1 << 2; // pow(2, 2)
// etc ...
Option.ALL    = Option.SHRINK |
                Option.MINIFY |
                Option.LINT;
Option.NUT    = Option.ALL &
                ~Option.LINT;


// test
alert([
  Option.SHRINK & Option.MINIFY, // 0
  Option.LINT & Option.MINIFY,   // 0
  Option.MINIFY & Option.MINIFY, // 2
  Option.SHRINK & Option.ALL,    // 1
  Option.LINT & Option.ALL,      // 4
  Option.MINIFY & Option.ALL,    // 2
  Option.ALL & Option.ALL,       // 7
  Option.SHRINK & Option.NUT,    // 1
  Option.MINIFY & Option.NUT,    // 2
  Option.LINT & Option.NUT,      // 0
  Option.ALL & Option.NUT        // 3
].join("\n"));

The easiest way to configure an object is via obj.option = Option.LINT | Option.MINIFY, as example, and we are sure that all associated operations will be performed ... how ? As example, with a switch :)
switch (!!obj.option) {
  case !!(obj.option & Option.ALL):
    // perform linting first
  case !!(obj.option & Option.NUT):
    // perform minification shrinking ?
    minify(
      obj.option & Option.SHRINK
    );
}
If we don't like the double not we can always use a function b(v){return !!v} and make it look gorgeous, isn't it?

Enough for this time

These are just few things I've been dealing with recently either with my projects or in some mailing list. More will come as soon as I spot it, of course ... right now, just think about these patterns and hint, maybe your code could make more sense, becoming more readable, easier to maintain, future proof, and all this with very little extra effort. Have a nice week end.

Friday, October 12, 2012

All Right, Gentlemen!

... this is after my latest post, just to summarize with a bit of humor my thoughts on developers getting easily excited with new stuff :D

Once again, not everything is wrong with TypeScript, but this is how I have really felt as soon as I have heard about this yet another JS superset and after a quick analysis through examples.

better if deca



learn twice



a better web



without standards

Thursday, October 11, 2012

JavaScript Made Everyone Crazy

Nobody seems to be happy, nobody seems to understand it ... everyone is trying to change it, pretending to make it better ... and again, nobody seems to realize it has been here since ever, it has been working in any field, it does everything, and it keeps getting faster!

One Scripting To Rule Them All

As simple as that: Dart compiles into JavaScript so does Java, CoffeeScript, C, C++ and any LLVM compatible/compilable language via Emscripten ... and now TypeScript too ... how cool is that? As tweeted before, if every programming language can be basically translated into JavaScript which is already an extremely high level scripting language, don't ya think that maybe is not exactly JavaScript the problem ? Don't ya think maybe it's time to learn it rather than keep moaning about it ? Hasn't this language already demonstrated to be one of the most malleable, powerful, adaptable, reusable, recyclable, expressive out there ? So why everyone is trying to pretend this language is not good? Why everybody wants this language to be something nobody needed until now or something that different?

What Is Wrong With TypeScript

I don't know where to start here ... but I'll try to make few points based on examples, OK? Please bear with me, you'll get it too.

Type Inconsistencies

Ironically, this is the very first point. Consider these two functions:
// note that string is written lowercase
function primitive(s:string):void {
  console.log(s);
}

// note that String is written PascalCase
function wrapper(s:String):void {
  console.log(s);
}
Now, with this "revolutionary brand new language" I ask you two simple questions and you should be able to answer me without testing, OK?
  1. will this call produce an error? primitive(new String(""))
  2. how about this one? wrapper("")
The truth is: there is no way to enforce the usage of a wrapper ... a language born to put on a scripting language types, is not strict with types themselves. string accepts primitives only, those that typeof(s) === "string" but String accepts both primitives and wrappers ... so basically, the most basic problem about JS is still there and developers are not encouraged to understand the difference between new String and just "string", they will put String everywhere feeling like they know what they are doing ... they are using classes ... WOOOOOOOW! Even more funny is the usage of bool rather than boolean, so that even what you know about JS does not work anymore ... so I guess Bool would be at least available, right?
The name 'Bool' does not exist in the current scope
Exactly, Boolean is the wrapper for bool: congrats! What do you say? It was to speed up typing? ... that's why you wanted types, to write less? ... wait ... what?

Fake Security

If you believe that typed code means better code quality, you are wrong. Typed code usually means that the developer knows types in advance ... that's pretty much it. In this attempt, where code is not resolved runtime, only types are, the feeling you are safer than before is natural ... well, you are not
function wtf(s:string):number {
  return s.charCodeAt(0);
}
Above function contract is extremely simple for both input and output ... too bad TypeScript cannot do much when it comes to calling the function, understanding that maybe that input has no char in index 0 so that wtf("") will produce a lovely NaN able to screw the rest of the logic because guess what ... NaN is considered a number: congrats again, another problem kept with TypeScript! Anyway, the latter example shows that it does not matter if input and output types are OK, it matters the logic. The fact String#charCodeAt returns a number does not mean that using it is safe. Same thing is with function s(o:Object):string {return o.toString();} which can easily fail with an object created through a null prototype, you know what I mean? This cannot be solved during translation time ... sorry for that!

Getting Worst On Security

In order to maintain decent performances, TypeScript tries to translate potatoes in potatoes ... which means, not too much magic, neither 17.000 lines of JavaScript are needed to simulate something JS is not, both ES3 and ES5. This time, I am talking about private attribute in classes and here an example:
class Point {
  // private they say ...
  private test:bool = false;
  constructor(
    public x:number,
    public y:number
  ) {}
  method():number {
    return this.x * this.y;
  }
}

class ColoredPoint extends Point {
  constructor(
    x:number,
    y:number,
    public color:string
  ) {
    super(x, y);
  }
  method():number {
    return 2 * super.method();
  }
}
What I am going to show you, is the demonstration that private in TypeScript is the last thing ever you can rely on:
// a lovely colored point
var cp = new ColoredPoint(
  10, 10, "test"
);

console.log(cp.color); // test

// accessing the private property
// from an extend, so not from the
// class it has been defined private
console.log(cp[cp.color]); // false

// setting the private property
cp[cp.color] = true;

// funny enough, this would be the same
cp["test"] = true;

console.log(cp[cp.color]); // true
Et voilà, mesdames et messieurs, private in TypeScript is and will always be a lie, for the simple reason JavaScript is that highly dynamic language you don't want to learn which is highly dynamic indeed. If you know JavaScript, you know also how to make things truly private when necessary ... in a much more reliable, secure, and meaningful way than what is offered here.
Repeated History? This kind of attack to private properties, obj.pvt VS obj["pvt"], was possible with ActionScript 2 as well ( damn it ... was it 2003 or 4? can't remember ). Adobe in that case did something similar TypeScript, Dart, or CofeeScript are trying to do to JavaScript but with ActionScript 1: it added sugar on top that was giving nothing to the language. This was because AS1 could already represent basically everything AS2 was able to do (AS2 was based on ECMAScript 4 same as C#, Silverlight, Air, and AS3). Moreover, AS2 has never been safer, better, smaller, or faster. It has been actually an epic fail since it has been replaced by AS3 the year after which was incompatible with AS1 and the reason I have abandoned Flash development: nothing better, just more pain in the ass! Cross platform problems were still there but a whole new language and namespaces to learn ... WOHOAW, and goodbye! ActionScript 1 has been a great product and it was 99% like JavaScript. This language that made Flash the most powerful and popular plugin ever changed, and the plugin is slowly dying since that time indeed ... I hope JavaScript won't do the same because for more than 12 years it has been just awesome and is still there, today more than ever, catching up with everyday modern/real-world challenges and without a glitch!

Translated Parent Accessor

One thing TypeScript got right about classes! Thanks gosh it did not attach anything to the prototype or each instance such this.super() and similar bullshit ... well done! But suddenly, "le wild WTF appears": super in the generated JS code, is the function, the constructor, and not the prototype, so that any super.methodName() call is translated into ParentFunction.prototype.nethodName.call(this)! This means that every super call will perform two lookups and will not ensure that the parent prototype cannot and should not be redefined runtime ... is that what TypeScript would like to be compatible with? I hope no ... so that constructor a part, in this way, every method of every class is penalized with performances and only the constructor has direct access: potentially O(methods * eachClass) rather than just O(classes) prototype lookups.

The Increased Performance Myth

The funny thing about TypeScript, is that basically the only real and concrete advantage of typed languages, the cost free and great improvement performance speaking, is completely absent. Not only all these typed checks are performed during translation and never again, but the tiny abstraction of the syntax requires more code than needed, as more closures than needed, as more memory, operations, function calls than needed so, in few words, performance is worst than before. OK, is not as bad as the whole Dart library moved in mobile devices, but still slower than good old JavaScript with or without common, well known, libraries.

No Benefits At All

After this analysis of "the latest coolest hybrid version of JavaScript", I believe things are clear:
  • more to write because of types (that's OK), more to learn, because of a new behavior specified in a 0.8 draft (that's not OK)
  • no concrete advantages over common JavaScript and its well known shenanigans: DOM still a mess, wrapper VS primitives, undefined and null or NaN, operators and other stuff too ... just YAGNI sugar that supposes to make us happy and dunno why
  • new shenanigans as it is for every bloody programming language ... so we have to be careful with both TypeScript and double check the equivalent generated JavaScript to be sure things are OK and as expected for real: double learning, OMG!
  • performance is worst ... maybe JIT compilers could somehow take advantage of TypeScript generated code but I don't think so plus is more code than needed as it is for every translator: not optimized, rarely faster
  • we can have mapped source code with TypeScript, we cannot have double mapped source code to understand errors if we would like to chose a different minifier over the TypeScript generated JS code
  • more I haven't talked about ...

Not All Wrong Neither

I know this post looks like I am throwing stones to MS intent and effort over this TypeScript tool / thing / language / proposal / whateveritis but I am not, I swear. I love the direction Microsoft is taking since IE9 but I have also said, and it wasn't just me, that the Web needs something else which is not sugar. Cool tools for debugging are all welcome ... new tools for something that does not solve a thing are a waste of time. We would like tools to make the Web better for every browser, faster for every CPU, graphically shiny for every screen ... classes for massive apps won't help anyone to make this happen and we all have the proof today that JavaScript never needed classes to scale, what we need are developers that know the language, use it properly, and move the web forward, rather than being stuck with sugar and sugar and sugar and sugar ... IMHO!

Everyone Is Crazy

Scripting Languages suppose to be easy, expressive and powerful, and JavaScript is one of them. The fact it has no classical inheritance is driving people crazy since ever: they need classes, that seems to be the only way they can think programming ... meanwhile, we all created what is the Web today and is far away from perfect but it's a great place and it's getting better on daily basis. Look what has been done ... think if strict types and classical OOP was the missing thing ... look again, and now move forward with your next, awesome, JavaScript based thing that will simply work everywhere and will satisfy your expectations! Thanks for reading, appreciated.

Friday, September 21, 2012

Web Viewport Size

if you ever had to deal with the full size of an HTML document, I know that feeling bro!

The Most Difficult Thing To Get Right Ever!

I mean, even google maps had some problem with that, preferring a user agent sniffing like technique rather than finding the real size of the window. This image is directly from latest Maximiliano Firtman post, a post you should read regardless this single topic!

The Useless window.screen

The object you might decide to check for is completely pointless for this purpose ... and the reason is simple: screen does not give any meaningful number to the Web field. The size of the screen in pixel means nothing when the viewport meta tag is set to scale 1, as example. The size means nothing in any case since it's about the full size of the screen and not the current DOM, viewport, window, size. The availWidth/Height property isn't that trustable neither, URL bar on the top or on the bottom, or both, could be in place ... how you gonna deal with that ...

Not only screen Problems

The webOS browser is a freaking cool one and still more recent than many other Webkit stock browsers stuck in some android 2.3.something ... so why would you drop webOS support now? Most likely, is gonna be just another slice of compatible devices you gonna have in your portfolio. Well, webOS, and I am talking about Palm Pre 1 and 2, has an horrible bug: you change orientation, things start zooming in and out out of control ... WHY??? Gosh it tok a while to understand how to fix it ... still no idea "why" thought!

Full Screen and iOS 6 safari Mobile

Problems ain't solved with latest Apple Operating System, actually ... problems are more than expected. The new 'full screen" feature provided by iOS6 does not obviously fire the "orientationchange" event, it fires "resize" one once in full screen and does not fire a thing once it goes back ... here again google maps trusting user agent sniffing like based approach: How lovely is that massive, wasted, white rectangle at the bottom ? What basically every single Web app is doing wrong right now, is to increase the full screen size by those (in)famous 60 pixels so that after they can call window.scroll(0, 0); ... well, all these software must be updated in order to understand that full screen, does not mean navigator.standalone neither means that the height of the document should be increased by 60 ... got it?

IE 6, 7, 8, and 9 Mobile WTFucks!!!

Best part is about these browsers ... specially the mobile one, at least in my Samsung WP7 Omnia Phone, I had to decrease the height by 75 pixels when in portrait, and 5 pixels while in landscape ... and that was completely random but ... you know, it worked :D For all other Desktop IE < 9 versions well ... many fixes and shit about scroll bars but hey ... I don't care, I think I have solved almost everything!

The Test Case

Well it's kinda simple, you check this page, and you see a 1 red pixel as full screen border no matter what Mobile or Desktop browser you are using ... it should just work and please let me know if it does not, thanks!

The Module

It's part of a repository I am keeping updated with completely random, but tested, stuff ... here it is, a 1.57KB (843 bytes gzipped) piece of code that could make your full screen life much easier, isn't it?

How Does It Work

Well, the index.html source code should give you some hint but here the basic:
window.addEventListener("viewportsize", function (e) {
  // here you change what you want
  // the 'e' object will have a 'result' property
  // containing width and height, e.g.
  myCanvas.width = e.result.width;
  myCanvas.height = e.result.height;
}, false);
Above example will make your canvas full screen no matter which device is running it .. aint that cool!

Freaking Flicking

Oh well, unfortunately to avoid problems in many good old Androids and webOS, plus Windows Phones too, the hidden body is necessary. Just try to imagine and consider that switching between landscape and portrait orientation is not such common thing ... usually that's performed when there's something wrong with the layout so ... you rather improve your layout skills here ;)

Android URL Bar

Yeah, I don't care ... I mean, Android phones have bigger screens than iPhone and iPod, so if iphone full screen once pinned is enough, Androids phones are OK as they are too. Thing is, ther eis no standard between stock and non stock browsers with the URL bar size so, rather than guessing or thinking cool, it's this Android, must go for N pixels I prefer focus actually only on those Androids phones that eventually have really no space at all, in therms of pixels, to show something meaningful. Small screens are welcome for tests and debug, Galaxy S3 with full screen option .. YAGNI!

Why Is This Important

Well, I guess if you reached this part you know already but here the thing ... sometimes you don't want the browser to scroll, the body to grow, your app to be unmanaged by the default browser scroll system, your game to be moved around, your designe to not be full screen ... did I forget anything here? :) Have fun with full screen Web Apps and please let me know if your device doesn't work, thanks!

Wednesday, September 12, 2012

wannaqu.it - one button web app to track activities

This is a truly simple web application I am still improving but I believe it's ready to be tested for all of you :)

wannaqu.it



The purpose of this app is to track an activity.
First of all, if you want to take full advantage and be able to use this app offline, pin it into your Home and you'll be free by network problems forever.

That's correct, there is nothing, absolutely nothing stored online ... it's your data, it's you tracking it ... no magic behind and 100% anonymous.

How Does It Work

As easy as that: you press the button once when you do something. By default, something is smoking, but it could be drinking or really, anything else you can imagine.

How To Read Data

The graph will look weird at the very beginning ... well, you have to feed your own data in a meaningful way so it takes a while ...
The graph is based on absolute time, rather than relative, and it keeps changing over the week, hours, month.
The goal of your activity is to reduce it to zero so ... a good graph, is a graph that does not exist.
This is if you really want to quit, otherwise you can play with your data without problems.

Why Absolute Time

Let's imagine you really would like to cut down cigarettes, OK? Now, it's Friday, 11:55pm, you had already few drinks, and you have a cigarette. Surely over a night out that graph will increase, you know it's true ... right?
Well, this graph should never give you the illusion you are doing OK ... which means, at midnight, there's no way you gonna have a fresh new clean column ... no, the purpose is to reduce, and to reduce over the time.
This time, your last 24 hours, is considering all those cigarettes ... deal with that, it's you smoking!

What If I Cheat

This is your problem, I cannot help if you cheat your same data, sorry.

Does It Work

I don't know ... I quitted smoking last Friday and I am pretty happy to have a clean graph ... but I swear I have tried to cut down before and every week end was again a mess ... so yeah, the best way to quit, is just quit I guess, but if you want to try cutting down and see if that works for you, now you have the easiest way ever to do it :)

Happy WebApp, and take care!

Wednesday, September 05, 2012

A Meaningful Client Side Alternative To node require()

TL;DR

Here you have the solution to all your problems ... no? So take a break, and read through :)

Current Status

Using a generic "module loader" for JavaScript files is becoming a common technique, and full of wins, not only on the node.js server side. There are different client side alternatives, not entirely based over the module concept, and apparently only one concrete proposal, called AMD, able to work in both server and client following a build/parsing procedure.
However, as somebody pointed out already ...

AMD is Not the Answer

This post does not even tell everything bad about AMD problems, and I am getting there, but it's surely a good starting point.
Tobie article is another resource that inspired somehow what I am going to propose here, so before discriminating this or that technique, I hope you'll find time to understand the whole problem ... found it? Let's go on then :)

The Beauty Of node.js require Function

I don't think I should even spend many words here ...

// module: compress

// in the global scope, it's just a module
// so no pollution to the global/window object
// no need to put everything in yet another closure
var fs = require("fs");

// just as example
this.compress = function (file, fn) {
fs
.createReadStream(file)
.pipe(
// check this out!
require("zlib").createGzip()
)
.pipe(
fs.createWriteStream(file + ".gz")
).on("close", function () {
var content = fs.readFileSync(file + ".gz");
fs.unlinkSync(file + ".gz");
fn(content);
})
;
};

So basically, with a synchronous require(module) call we can decide whenever we want where that module should be included in our logic. This means we don't need to think in advance to all needed dependencies for our current module, as well as this doesn't require to split in many nested functions our asynchronous logic.
Look at above example ... in node world the require("fs") is performed basically in every single module ... the FileSystem is that important, hell yeah!
We dont' care much about requiring it at the very beginning of above stupid module 'cause surely that operation will cost nothing! Each module is cached indeed so there's actually zero impact if we use a require hundreds of time inline ... really, it's that fast, but the very first one might cost a bit.
This is why require("zlib") is loaded only once, and only when it's needed ... so that memory, disk, cpu, and everything else, can live in peace before the very first call of that exported method while after that, that call will cost again nothing.

Is a mandatory nested function call through AMD logic as fast as above example? I tell you, NO, but this is not the real problem, is it?

AMD Does Not Truly Scale

... as simple as that. If you need a build process behind something that could fail in any case, I would say you are doing it wrong. I am talking about current era, where internet connection could be there or not ... I am talking about mobile and I give you a very basic example.
I have created my freaking cool website or webapp that loads asynchronously everything and I am on the road with my supa-dupa smart phone.
When "suddenly, le wild spot without internet coverage appears"!
Now I press that lovely button in the lovely application that loads asynchronously the lovely next part of my action and guess what happens ... are you there? Nothing!
That instant without my mobile network will screw up my flow, will break my action, will let me wait "forever" and in most common cases, it will block me to use properly the app.
Of course, if that action required server side interaction, that action won't work in any case ... but how come I don't even see a notification? How come pieces of my application are not showing up telling me that there is actually a problem, rather than letting me wait without any notification, 'couse probably even notification logic was created as AMD module?

And what if connection is simply bad? The whole application or website is responding decently but that part, oh gosh how much I was planning to use that app part, is taking ages to load! How would you feel in front of such program?

AMD Resolves Lazy/Circular Load Synchronously

That's correct ... gotcha! Have you ever read what you should do in order to resolve modules that load asynchronously other modules inside themselves?

//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if a also asked for b,
//a circular dependency.
return function(title) {
// me: Excuse me ... WUT?
return require("a").doSomething();
}
}
);

So here the thing, if "by accident" you have a circular dependency you should use require() as node.js does ... oh well ...

On Circular Dependencies / Cycles

This topic is one of the biggest paradox about programming ... we try to decouple everything, specially when it comes to write modules, so that not a single part of the app should be aware of the surrounding environment ... isn't it? Then someone said that circular dependencies are bad ... but how come?
Here an example, a truly stupid one:
Hi, I am a human, the human module, and I am completely sufficient, but I need to go in a place that would take too much by my own ... so I need the module car.

Hi, I am a car, the module car, and I am fabulous by my own, but I need the module human to be able to go somewhere.

A partner, better than a car, could also explain the fact we actually think in circular references all the time ... am I wrong?
The AMD take in this case is that "we should change the require logic when this happens and we should be aware in advance in order to solve this" ... yeah, nice, so now in AMD we have two ways to require and return what we export ... and once again, in my humble opinion, this does not scale ... at all!

Double Effort, Double Code!

With AMD we don't only need to change our AMD code/style/logic when things are not known in advance, as showed before ... we also need to write code for modules that is not compatible with node.js, resulting in such piece of redundant code that I believe nobody truly want to write more than once in a programmer life.
Take an excellent library as lodash is, and check what it has to do in order to be compatible with AMD too ...

// expose Lo-Dash
// some AMD build optimizers, like r.js, check for specific condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash was injected by a third-party script and not intended to be
// loaded as a module. The global assignment can be reverted in the Lo-Dash
// module via its `noConflict()` method.
window._ = lodash;

// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define(function() {
return lodash;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports) {
// in Node.js or RingoJS v0.8.0+
if (typeof module == 'object' && module && module.exports == freeExports) {
(module.exports = lodash)._ = lodash;
}
// in Narwhal or RingoJS v0.7.0-
else {
freeExports._ = lodash;
}
}
else {
// in a browser or Rhino
window._ = lodash;
}

Now ... ask yourself, is this what you want to write for every single module you gonna create that might work in both server and client side?

Combined AMD Modules

Here another possibility, super cool ... we can combine all modules together into a single file: YEAH! But if this what you do for your project, don't you wonder what is the point then to use all those "asynchronous ready" callbacks if these will be executed in a synchronous way in production? Was that different syntax truly needed? And what about JS engines parsing time? Is processing the whole project at once in a single file a good thing for both Desktop and Mobile?
Why are you developing asynchronously with all those nested callbacks if you provide a synchronous build? Is the code size affected? Does all this make any sense?

AMD, The Good Part... Maybe

OK, there must be some part of this logic that conquered many developers out there .. and I must admit AMD "solved with nonchalance" the fact JavaScript, in the client side, has always had problems with the global scope pollution.
The fact AMD forces us to write the module inside a function that receives already arguments with other needed modules, is a win ... but wait a second, wasn't that boring before that nobody until now wrote a single bloody closure to avoid global scope pollution?
I think AMD is a side effect, with all possible noble and good purpose, of a general misunderstanding of how is JS code sharing across libraries.
Let's remember we never even thought about modules until we started clashing with all possible each other polluting namespaces, global variables, Object.prototype, and any sort of crap, thinking we are the only script ever running in a web page ... isn't it?
So kudos for AMD, at least there is a function, but where the hack is the "use strict" directive suggested for every single bloody AMD module in any example you can find in the documentation? where is the global pollution problem solver, if developers are not educated or warned about the problem itself?

node.js require ain't gold neither

When network, roundtrips and latency come into the game, the node.js require() solution does not fit, scale, work, neither.
If you understand how Loading from node_modules Folders logic works, and you have an extra look into All Together diagram, you will realize that all those checks, performed through an HTTP connection, won't ever make sense on the client side.
Are we stuck then? Or there's some tiny little brick in the middle that is not used, common, public, or discussed yet?

A node require() Like, For Client Side

Eventually, here where I was heading since the beginning: my require_client proposal ... gosh it took long!
Rewind ... How about having the best from all techniques described "here and there" in order to:
  • avoid big files parsing, everything is parsed once and on demand
  • provide an easy to use builder for production ready single file code
  • use one single syntax/model/style to define modules for both node or client side
  • solve cycles exactly as node does
  • forget 10 lines of checks to export a bloody module
  • organize namespaces in folders
  • obtain excellent performance
  • make a single file distributable
... and finally, compare results against all other techniques?
Here, the AMD loader, versus the inline and DOM script injection loader, versus the dev version of my proposal, and finally the production/compiled version of my proposal ... how about that? You can use any console, profiler, dev tool/thing you want, to compare results, it's about a 150Kb total amount of scripts with most of them loaded ASAP, and one loaded on "load" event.
You can measure jquery, underscore, backbonejs, and the ironically added as last script head.js script there within their loading/parsing/ready time.

Reading Results

If you think nowadays the DOMContentLoaded event is all you need to startup faster your web page/app, you are probably wrong. DOMContentLoaded event means almost nothing for real UX, because a user that has a DOM ready but can't use, because modules and logic are not loaded yet, or see, because CSS and images have not been resolved yet, the page/app, is simply a "user waiting" rather than interacting and nothing else.
Accordingly, if you consider the code flow and the time everything is ready to be used, the compiled require() method is the best option you have: it's freaking fast!

"use strict" included

The best part I could think about, is the "use strict"; directive by default automatically prepended to any module that is going to be parsed.
This is a huge advantage for client side code because while we are able to create as many var as we want in the module scope, the engine parser and compiler will instantly raise an error the line and column we forgot a variable declaration. All other safer things are in place and working but .. you know, maybe you don't want this?
That's why the require_client compiler makes the strict configuration property easy to spot, configure, and change ... as long as you know why you are doing that, everything is fine.

How Does It Work

The compiler includes a 360 bytes once minzipped function that when is not optimized simply works through XHR.
This function could be the very only global function you need, since every module is evaluated sandboxed and with all node.js module behaviors.
You can export a function itself, you can export a module, you can require inside a module, you can do 90% of what you could do in a node.js environment.
You don't need to take care of global variables definition, those won't affect other modules.
What you should do, is to remember that this is the client so the path you choose in the development version, is the root, as any node_modules folder would be.
If you clone the repository, you can test via copy and paste the resulting build/require.js in whatever browser console traps such require_client ~/folder_you_put_staff/require_client/js or require_client ~/folder_you_put_staff/require_client/cycles.
require("a") in the first case and require("main") in the second.
In order to obtain a similar portable function you should create a folder with all scripts and point to that folder via require_client so that a script with all inclusions will be created.

A Basic Example

So here what's the require_client script is able to produce.
Let's imagine this is our project folder structure:

project/
css/
js/
require.dev.js
index.html

The index.html file can simply have a single script in its header that includes require.dev.js and the bootstrap module through require("main");, as example.
So, let's imagine we have module a, b, and main inside the js folder, OK?
require_client project/js project/require.js
This call will produce the require.js file such as:

/*! (C) Andrea Giammarchi */
var require=function(c,d,e){function l(n,m){return m?n:g[n]}function b(o){var m=a[o]={},n={id:o,parent:c,filename:l(o,h),web:h};n[k]=m;d("global","module",k,(e.strict?"'use strict';":"")+l(o)).call(m,c,n,m);j.call(m=n[k],i)||(m[i]=h);return m}function f(m){return j.call(a,m)?a[m]:a[m]=b(m)}var k="exports",i="loaded",h=!0,a={},j=a.hasOwnProperty,g={
"a": "console.log(\"a starting\");exports.done=false;var b=require(\"b\");console.log(\"in a, b.done = \"+b.done);exports.done=true;console.log(\"a done\");",
"main": "console.log(\"main starting\");var a=require(\"a\");var b=require(\"b\");console.log(\"in main, a.done=\"+a.done+\", b.done=\"+b.done);",
"b": "console.log(\"b starting\");exports.done=false;var a=require(\"a\");console.log(\"in b, a.done = \"+a.done);exports.done=true;console.log(\"b done\");"
};f.config=e;f.main=c;return f}(this,Function,{
strict:true
});
Now the index.html could simply include reuiqre.js rather than the dev version ;)
Above program is the same showed in node.js API documentation about cycles. If you copy and paste this code in any console and you write after require("main"); you'll see the expected result.
As summary, require_client is able to minify and place inline all your scripts, creating modules names based on files and folders hierarchy.
All modules will be evaluated with a global object, already available, as well as module, exports, and the latter used as the module context.
The simple object based cache system will ensure these modules are evaluated once and never again.

What's YAGNI

Few things, that could change, are not in on purpose. As example, the module.parent is always the global object, since in fact, it's in the global scope, through Function compilation, that the module will be parsed the very first time. Not sure we need a complicated mechanism to chain calls and also this mechanism is error prone.
If you have 2 scripts requiring the same module, first come, first serve. The second one should not affect runtime the already parsed module changing suddenly the module.parent property ... you know what I mean?
The path resolution is a no-go, rather than trying to fix all possible messes with paths and OS, put your files in a single JS folder and consider that one your virtual node_modules one for clients.
If you have folder links inside the JS folder it's OK, but if you have recursive links you are screwed. Please keep it simple while I think how to avoid such problem within the require_client logic, thanks.

What Is Not There Yet

If your project is more than a megabyte minzipped, you might want to be able to split in different chunks the code so that the second, last, injected, require, won't disturb the first one. This is not in place yet since this free time project was born for a small/medium web app I am working on that will be out pretty soon ... an app that surely does not need such amount of code as many other web app should NOT ... but you know, I've been talking about scaling so much that a note about the fact this solution won't scale so nicely with massive projects is a must say.

UpdateJust landed a version that does not cause conflicts with require itself. The first defined require will be the one used everywhere so it's now possible to name a project and include it in the main page so ... parallel projects are now available ;)

If you would like to reuse node modules that work in the client side too, you needto copy them inside the path folder.
The configuration object is the one you can find at the end of the require.js file ... there are two defaults there, but you can always change them via require.config.path = "different"; as well as you can drop the require.config.strict = false; directive so that modules will be evaluated without "use strict"; directive.
Anything else? Dunno ... you might come up with some hint, question, suggestion. And thanks for reading :), I know it was a long one!

Last Thoughts

If AMD and RequireJS comes with a compiler able to make everything already available somehow, think how much pointless become the optimization once you can have already available all dependencies without needing to write JS code in a different way, regardless it's for node.js or the client web normal code.
There are NOT really many excuse to keep polluting the global scope with variables, we have so may alternatives today that keep doing it would result as evil as any worst technique you can embrace in JS world.