miércoles, marzo 06, 2013

var self=this is not lame!

A few weeks ago I came across this article: http://ngauthier.com/2012/04/var-self-equals-lame.html and then I thought: "OK, let's follow this stranger's advice, I don't want to be lame!".

But what was really lame was to change my coding style just because other person said so. After thinking a little bit about it and writing some code; I found that the reasons given in the aforementioned article weren't very good...
  • Intent. self is totally unambiguous, and when you see a self it's very clear that it refers to a lexically scoped variable rather than a variable that might change at runtime.
  • Self-completeness. Why is 'leaning on a well tested library' good, when you could be using a core language feature instead?
  • Brevity. Oh, a one liner. SLOC's is the most simplistic (and usually wrong) metric for code complexity. Let's take another approach and count levels of nested parens and braces instead! I prefer reading two lines containing simple statements over a complex expression almost every time, because our brain handles poorly deep nesting.
  • Dangling code. I have to agree in that, but that's a minor problem and cleaning up unused variables is a task that we all have to face when refactoring code.
And there are some very good reasons to prefer self=this over bind(this):
  • Debugging. What do you see if you inspect a callback function variable that has been bound? This: function () { [native code] }. You don't get any information about which function is it, because all you see is a native code wrapper.
  • Nested callbacks. You have to bind two functions, even if you just use this in the inner callback.
  • "this" as as part of the callback API. Some callbacks will set a useful value for "this" (like the receiver of an event, or the current element in $.forEach); what if you want to use it?
So, emotional statements (like "don't do that, it is lame!") don't really belong to science or programming, as they bias your criteria. Avoid them.