HyperTextMatters
6 January 2006
 
EIBTI for Javascript: explicit is better than implicit
Post a comment (login required)
Javascript's "prototype" driven nature allows programmers to alter the behavior of built-in types thusly:

String.prototype.isEmpty = function() { return /^\s+$/.test(this); }

Just because you can, doesn't mean you should though.  For instance, a method you add to String's prototype might require two arguments, but a future update to the language itself might add the very same method with the arguments reversed.

Consider this alternative:

function FormValue(str) { this.str = str}
FormValue.prototype.isEmpty = function() { return /^\s+$/.test(this.str); }
var test = new FormValue(" ");

Note you must explicity instantiate a FormValue instance, rather than implicitly operating on a String (primitive).  Consider this a feature.  For instance, Python has popularized the acronym EIBTI, or "explicit is better than implicit."  No wonder MochiKit, "a production-quality framework that brings powerful and well-known Python idioms to JavaScript," rightfully leaves String.prototype alone.
Posted by htmatters at 11:55 AM | Comments (2)
 
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: EIBTI for Javascript: explicit is better than implicit
Yes, and now to check the value of test, you can't
simply say

if (test == 'my test value')

since the default toString method of Object is the string
"[Object object]"

Posted by n on January 6, 2006 at 5:57 PM

Re: EIBTI for Javascript: explicit is better than implicit
In the spirit of Einstein's edict to "make everything as simple as possible, but not simpler" just override toString

Posted by htmatters on January 6, 2006 at 6:47 PM

Post a comment (login required)