<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>davidflanagan.com</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/" />
    <link rel="self" type="application/atom+xml" href="http://www.davidflanagan.com/atom.xml" />
    <id>tag:www.davidflanagan.com,2008-10-28://1</id>
    <updated>2009-12-07T23:13:52Z</updated>
    <subtitle>books for programmers</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.21-en</generator>

<entry>
    <title>Closures in Java 7 After All</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/12/closures-in-java-7-after-all.html" />
    <id>tag:www.davidflanagan.com,2009://1.182</id>

    <published>2009-12-07T22:30:49Z</published>
    <updated>2009-12-07T23:13:52Z</updated>

    <summary>I&apos;ve been focusing on JavaScript recently, so I missed this when it first came out: Closures for Java. I think it is interesting that the motivation for finally doing this is to facilitate APIs for concurrency. Sun will not be...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="java" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've been focusing on JavaScript recently, so I missed this when it first came out:<br />
<a href="http://blogs.sun.com/mr/entry/closures">Closures for Java</a>.  I think it is interesting that the motivation for finally doing this is to facilitate APIs for concurrency. <br />
Sun will not be using any of the existing closures proposals as a starting point, but their initial ideas are perhaps closest to the FCM (first-class methods) proposal.</p>

<p>There are <a href="http://blogs.sun.com/mr/entry/closures_qa">further details here</a> including the ominous admission by Sun that they don't feel they can get any JSRs (for closures, Project Coin, or Java 7) approved by the JCP until they resolve their dispute with Apache.  In the meantime, development of closures and the Coin extensions is happening outside of the JCP in the OpenJDK.</p>

<p> In <a href="http://mail.openjdk.java.net/pipermail/jdk7-dev/2009-November/001054.html">related news</a>, the schedule for OpenJDK7 has slipped and a final release is now due in September 2010.  Note that this is the schedule for the JDK7, not for Java 7. </p>]]>
        
    </content>
</entry>

<entry>
    <title>A module loader with simple dependency management</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/a-module-loader.html" />
    <id>tag:www.davidflanagan.com,2009://1.180</id>

    <published>2009-11-25T20:15:11Z</published>
    <updated>2009-11-25T20:37:46Z</updated>

    <summary>I&apos;ve written another version require2.js of my CommonJS module loader require() function. This one has two interesting features. First, you can &quot;pre-load&quot; modules by mapping the module filename to the module function in the require._module_function object. If you do this,...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've written another version <a href="http://www.davidflanagan.com/demos/require2.js">require2.js</a> of my CommonJS module loader require() function.  This one has two interesting features.</p>

<p>First, you can "pre-load" modules by mapping the module filename to the module function in the require._module_function object.  If you do this, then the module will not need to be loaded.  For example:</p>

<pre>
require._module_functions['math.js'] = function(require,exports,module) {
     // Code for the math module goes here
};
</pre>

<p>Second, this new version of require() has a require._print hook, which, if set to a suitable function, will print out the text of all modules it loads, wrapped in a function and assigned to the require._module_function map as above. You can even define a require._minimize hook if you want to do code minimization on your modules.</p>

<p>I've defined another script <a href="http://www.davidflanagan.com/demos/display_requirements.js">display_requirements.js</a> that defines suitable _print and _minimize functions.</p>

<p>So, here's the upshot.  For relatively simple applications that load modules statically at start up, use the require2.js script for loading modules.  Its inefficient, but works well during the development phase.  Then, when you're getting ready to deploy your application, load the display_requirements.js script after loading require2.js but before you actually call require() anywhere.  This will cause a big chunk of code to appear at the bottom of your web page--pre-loaded minimized versions of all the modules you used.  Cut-and-paste this code into a new file named requirements.js (or even paste it at the bottom of require2.js) and load the requirements.js script in place of the display_requirements.js script.  Now you can continue to use require() as you have always done, but it won't have to hit the network to load your modules.</p>

<p>I haven't done much deployment of real-world web applications, and am not qualified to say whether a system like this would actually be helpful in practice. But it was an easy tweak to my existing code, so there it is.</p>]]>
        
    </content>
</entry>

<entry>
    <title>CommonJS Modules implementation</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/commonjs-module.html" />
    <id>tag:www.davidflanagan.com,2009://1.179</id>

    <published>2009-11-24T23:06:30Z</published>
    <updated>2009-11-25T21:36:23Z</updated>

    <summary>I&apos;ve implemented the CommonJS Modules 1.0 specification with the code in this file. It appears to pass the compliance tests when run in Firefox and Chrome on Linux, and also when run standalone in Tracemonkey, Rhino or V8. Note that...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've implemented the <a href="http://commonjs.org/specs/modules/1.0.html">CommonJS Modules 1.0 specification</a> with the code in <a href="http://www.davidflanagan.com/demos/require.js">this file</a>.  It appears to pass the <a href="http://code.google.com/p/interoperablejs/">compliance tests</a> when run in Firefox and Chrome on Linux, and also when run standalone in Tracemonkey, Rhino or V8.</p>

<p>Note that this implementation does not use the namespace probing technique I described in my <a href="http://www.davidflanagan.com/2009/11/functions-as-na.html">previous post</a>.</p>

<p><b>Update:</b> One of the things that really surprised me when testing my implementation was to discover that the CommonJS spec requires (this is not explicit in the specification text, but it is explicit in the conformance tests) the require() function to return the actual exports object of a module, and not make a defensive copy of it.</p>

<p>Suppose a program includes module A which includes modules B and C.  Module C can require B and then add, replace, or remove methods from B's API.  Later, when the program includes Module B directly, it will get the modified version of B.  In order to correctly use this modified module B, the programmer will have to read the documentation for module C!</p>

<p><b>Update 2:</b> There are great comments to this post, including a link to <a href="http://lucassmith.name/2009/11/commonjs-require-api-is-a-poor-fit-for-client-side-js.html">Luke Smith's blog post</a> that argues that the synchronous nature of CommonJS modules is not a good fit for client-side scripting.  In response I wanted to make clear that I posted this code because I thought it was interesting, not because I think that client-side programmers should go out and start using it right away.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Functions as Namespaces, and How to Peek Inside</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/functions-as-na.html" />
    <id>tag:www.davidflanagan.com,2009://1.178</id>

    <published>2009-11-21T07:15:21Z</published>
    <updated>2009-11-21T08:02:53Z</updated>

    <summary> It has become common in modern JavaScript programming to use functions as namespaces. If you put your code inside a function, then your variables and functions are local to the containing function and do not clutter up the global...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
It has become common in modern JavaScript programming to use functions as namespaces.  If you put your code inside a function, then your variables and functions are local to the containing function and do not clutter up the global scope.
</p>
<pre>
var value = (function() {  // Wrapper function creates a local scope or namespace
    // your code goes here
    return value;  // Export a value from the namespace
)());  // Invoke the wrapper function to run your code      
</pre>
<p>
Now suppose that you have some JavaScript code as a string--you've just loaded it using XMLHttpRequest, for example.  You're going to evaluate the code, and you might want to evaluate it in a namespace so that it doesn't define functions and variables in the global scope.  This is easy: just wrap it in a function before evaluating it.  In this case, the Function() constructor is even more handy than the eval() function:
</p>
<pre>
var code = ....;  // A string of JS code to evaluate
var f = new Function(code);   // Wrap it in a function
f();    // And run the function
</pre>
<p>
The problem with doing this is that the function creates a sealed namespace and we can't see what is inside.  If the code defines something useful like a function or a class, we can't access it, and it does us no good.
</p><p>
Here's a trick I've just discovered.  (I'm sure someone else has thought of this, but I haven't seen it used or described elsewhere).  Before you wrap your code in a function add this line to it:
</p>
<pre>
return function(s) { return eval(s); };
</pre>
<p>
Now, when you invoke the wrapper function, it returns this evaluator function to you.  The returned function evaluates a string <i>in the scope of the namespace</i>, so you can use it to peek into the namespace and extract whatever values you want!
</p><p>
If your string of code defines a constructor function named Set() that you want to use, you can run the code in a namespace and then extract f from the namespace like this:
</p>
<pre>
var code = readFile("Set.js");  // A string of JS code to evaluate
// Define and invoke a wrapper function with special suffix code.
// The return value is a namespace evaluator function and we treat
// it as a namespace object.
var setns = new Function(code + "return function(s) { return eval(s); };")(); 
var Set = setns("Set");  // Import the Set function from the namespace.
var s = new Set();  // Use the class we just imported
</pre>
<p>
And what if there are 3 values you want to extract from the namespace?
</p>
<pre>
// Extract an object containing 3 values from the namespace
var sets = setns('{Set:"Set", BitSet:"BitSet", MultiSet:"MultiSet"}');
var bs = new sets.BitSet();
</pre>
<p>
I've defined a namespace() function for loading code and doing this kind of namespacing automatically: </p>]]>
        <![CDATA[<pre>
/*
 * Load modules of code by enveloping them in a function and executing
 * the function: then they don't pollute the global namespace (unless they
 * assign to undeclared variables, but ES5 strict mode will prevent that.)
 * The wrapper function we create returns an evaluator function that 
 * evals a string inside the namespace. This evaluator function is the
 * return value of namespace() and provides read access to the symbols 
 * defined inside the namespace.
 */
function namespace(url) {
    if (!namespace.cache) namespace.cache = {};  // First call only
    if (!namespace.cache.hasOwnProperty(url)) {  // Only load urls once
        var code = gettext(url);           // Read code from url
        var f = new Function(code +        // Wrap code, add a return value
                             "return function(s) { return eval(s); };");
        namespace.cache[url] = f.call({}); // Invoke wrapper, cache evaluator
    }
    return namespace.cache[url];  // Return cached evaluator for this namespace
}

/* Return the text of the specified url, script element or file */
function gettext(url) {
    if (typeof XMLHttpRequest !== "undefined") { // Running in a browser
        if (url.charAt(0) == '#') {              // URL names a script tag
            var tag = document.getElementById(url.substring(1));
            if (!tag || tag.tagName != "SCRIPT")
                throw new Error("Unknown script " + url);
            if (tag.src) return gettext(tag.src);// If it has a src attribute
            else return tag.text;                // Otherwise use script content
        }
        else {                                   // Load file with Ajax
            var req = new XMLHttpRequest();
            req.open("GET", url, false);         // Asynchronous get
            req.send(null);
            return req.responseText;             // Error handling?
        }
    }
    else if (typeof readFile == "function") return readFile(url);  // Rhino
    else if (typeof snarf == "function") return snarf(url); // Spidermonkey
    else if (typeof read == "function") return read(url);   // V8
    else throw new Error("No mechanism to load module text");
}
</pre>
<p>
You can also find these functions in <a href="/demos/namespace/namespace.js">namespace.js</a>.  I've written a simple <a href="/demos/namespace/nstest.html">demo</a>.  It doesn't do anything interesting--just alerts 256.  But if you look at the code, you'll see that it loads and namespaces 4 chunks of code.
</p><p>
If you're a Python programmer you may be thinking that this technique would be useful for implementing a Python-style "from foo import bar" type module system.  I've been thinking the same thing and I'm working on it (but the code isn't ready to share).  The shortcoming, of course, is that there is no way to enumerate and import all the symbols defined in a namespace, so we can't simulate Python's "import *"
</p>]]>
    </content>
</entry>

<entry>
    <title>Google Closure Library and Optimizer</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/google-closure.html" />
    <id>tag:www.davidflanagan.com,2009://1.177</id>

    <published>2009-11-06T20:30:40Z</published>
    <updated>2009-11-06T21:11:52Z</updated>

    <summary> Google has open-sourced the javascript library and optimizer they use in gmail and other web applications. They call it &quot;Closure&quot; and you can read about it here. While the optimizer looks very cool, I think the library is most...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
Google has open-sourced the javascript library and optimizer they use in gmail and other web applications.  They call it "Closure" and you can <a href="http://code.google.com/closure/">read about it here</a>.
</p><p>
While the optimizer looks very cool, I think the library is most impressive.  Its a really large code base, and at least some of it has been thoroughly field-tested in gmail and similar applications.  You can get the code like this:
</p>
<pre>
svn checkout http://closure-library.googlecode.com/svn/trunk/ closure-library-read-only
</pre>

<p>
The closure library is intended to be used with the closure optimizer which removes unused code, so the APIs are broad with lots of methods--there is no sense that the closure developers were skimping on API in order to pack everything into a small download bundle.  Also, and perhaps for the same reason, the code is not full of micro-optimizations.  Compared to the jQuery and YUI code (for example) the Closure code is straightforward and easy to understand. 
</p>]]>
        
    </content>
</entry>

<entry>
    <title>My Ruby Book on your iPhone.  Cheap!</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/08/my-ruby-book-on.html" />
    <id>tag:www.davidflanagan.com,2009://1.176</id>

    <published>2009-08-24T22:44:45Z</published>
    <updated>2009-08-27T19:34:56Z</updated>

    <summary>O&apos;Reilly has just released The Ruby Programming Language as a standalone iphone app! Looks like you can get your hands on it for just $5 (The cover price of the print edition is $40.) I don&apos;t have an iphone, but...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="ruby" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>O'Reilly has just released <a href="http://www.amazon.com/gp/product/0596516177?ie=UTF8&tag=davidflanagancom&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177">The Ruby Programming Language</a><img src="http://www.assoc-amazon.com/e/ir?t=davidflanagancom&l=as2&o=1&a=0596516177" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> as a standalone <a href="http://appshopper.com/books/the-ruby-programming-language">iphone app</a>!  Looks like you can get your hands on it for just $5  (The cover price of the print edition is $40.)  I don't have an iphone, but if you do, I'd love to hear how the book looks and works for you in that format.</p>

<p>At the same time, O'Reilly has dropped the <a href="http://oreilly.com/catalog/9780596516178/">ebook</a> price for other readers from $30 to $10.  Amazon's Kindle price is still $18 today.  I don't know if that is going to go down or not. (<b>Update 8/27</b>: the kindle price is now $8.)</p>

<p>I'm not sure how I feel about O'Reilly using my book for their marketing experiments, but it's certainly a good deal for readers.  So I ask for your help in making up for the reduced price with a massive increase in sales volume!  :-)</p>

<p>And if I can engage in some more self-promotion: reviewers on Amazon think that this is the best book I've ever written.  The 26 reviewers have all given it a 5-star rating, and the most recent review goes over the top and calls it "the best ever written programming language book".   Wow.  You know you want it on your iPhone!  </p>

<p><b>Update:</b> my editor says that he thinks this new ebook price is a temporary sale.</p>]]>
        
    </content>
</entry>

<entry>
    <title>typeof, isFunction vs. isCallable, now and in ECMAScript 5</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/08/typeof-isfuncti.html" />
    <id>tag:www.davidflanagan.com,2009://1.175</id>

    <published>2009-08-24T18:09:41Z</published>
    <updated>2009-08-24T18:33:38Z</updated>

    <summary>Function objects in JavaScript are callable: you can invoke them. Other, non-function objects are allowed to be callable, however. Host objects in IE (things like Window.alert()) are callable, but are not native function objects. (Other browsers implement DOM methods as...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Function objects in JavaScript are <i>callable</i>: you can invoke them.  Other, non-function objects are allowed to be callable, however.  Host objects in IE (things like Window.alert()) are callable, but are not native function objects.  (Other browsers implement DOM methods as true native function objects).  Also, a number of browsers have followed Firefox's lead in making RegExp objects callable even though they are not functions.  Although you can invoke any callable object like a function, the difference is that callable objects don't have function methods call() and apply() (and bind() in ECMAScript 5).</p>

<p>Today, the typeof operator returns "function" for true function objects, and returns "object" for IE's callable host objects.  Most browsers return "object" for callable RegExps, but Safari returns "function", and Google Chrome is likely to follow Safari's lead on this.  If you want to be sure that something is a true function (and not a regexp) you can use something like this:</p>

<pre>
function isFunction(x) { 
    return Object.prototype.toString.call(x) === "[object Function]";
}
</pre>

<p>There is not today a reliable way to write an isCallable() function, however.</p>

<p>Things change in the ECMAScript 5 specification.  The typeof operator is required to return "function" for any native or host object that is callable.  When IE implements the spec, we can expect "typeof window.alert" to evaluate to "function".  The problem is that browsers like Firefox and Opera that have callable regexps are unlikely to implement the spec: the typeof operator on a regular expression will continue to return "object" for those browsers.  The committee writing the specification was aware of this problem, but ran out of time to fix it.</p>

<p>So today typeof x === "function" is close to an isFunction() test, but it fails for regular expressions in some browsers.  In ECMAScript 5, typeof will be close to an isCallable() test, but it will fail for regular expressions in some other browsers.</p>

<p>Fortunately, the isFunction() test above should continue to work in ECMAScript 5, and <br />
there is a way to write a reliable isCallable() function in ECMAScript 5.  It relies on the fact that the Array.prototype.forEach() method checks its argument for callability even when invoked on an empty array.  (So this isCallable() function assumes that browser vendors implement the Array.forEach() method as specified.)  Here it is:</p>

<pre>
Object.isCallable = function(o) {
    // Array.prototype.forEach throws TypeError for non-callable arguments
    try {
        [].forEach(o);  // o will never be invoked, but it will be tested for callabilty
        return true;
    } catch (x) {
        if (x instanceof TypeError) return false;
        else throw x;
    }
};
</pre>]]>
        
    </content>
</entry>

<entry>
    <title>Array.some is like forEach() with an early termination option</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/08/arraysome-is-li.html" />
    <id>tag:www.davidflanagan.com,2009://1.174</id>

    <published>2009-08-19T06:22:44Z</published>
    <updated>2009-08-19T06:43:46Z</updated>

    <summary>I was recently writing some documentation for the Array.forEach() method (part of ES5, but most browsers other than IE support it now) and worrying about the fact that there is no clean way to terminate the iteration prematurely. Nothing like...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I was recently writing some documentation for the Array.forEach() method (part of ES5, but most browsers other than IE support it now) and worrying about the fact that there is no clean way to terminate the iteration prematurely.  Nothing like the break statement, that is.  If you really want to get out of the loop, the function you pass to forEach() has to throw something.  And the forEach() method won't catch it for you, so you've got to write your own try block.</p>

<p>Then, when working with the new array predicate method Array.some(), I realized that we don't have to think of it as a predicate method.  If we ignore the return value, it is an iterator method that works just like Array.forEach() except that if your function returns true (or any truthy value) then the loop terminates.  So inside of the function you pass, a plain return statement with no value is like using a continue statement.  And "return true" is like a break statement, causing the loop to terminate. The implicit return that occurs at the end of the function body returns undefined, which is like returning false--it keeps the loop going.</p>

<p>The Array.every() method is not so useful this way: you have to explicitly return a truthy value to keep the loop going, so an implicit return at the end of the function body would act like a break statement.</p>

<p>The problem I see with using some() in this way is a stylistic one:  the name really doesn't look like the name of an iterator the way that  "each" and "every" do.<br />
</p>]]>
        
    </content>
</entry>

<entry>
    <title>Good algorithms are better than clever code</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/08/good-algorithms.html" />
    <id>tag:www.davidflanagan.com,2009://1.173</id>

    <published>2009-08-18T18:36:06Z</published>
    <updated>2009-08-18T18:48:23Z</updated>

    <summary>Yesterday, I posted an entry about a clever way to implement string multiplication in JavaScript using Array.prototype.join() In comments, redraiment challenged me, suggesting that an implementation based on string doubling would be more efficient. Sure, I thought, for really large...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Yesterday, I posted an <a href="http://www.davidflanagan.com/2009/08/string-multipli.html">entry</a> about a clever way to implement string multiplication in JavaScript using Array.prototype.join()</p>

<p>In comments, redraiment challenged me, suggesting that an implementation based on string doubling would be more efficient.  Sure, I thought, for really large values of n, but surely for small n, using the native join() method would be better, wouldn't it?</p>

<p>It turns out that writing a good algorithm is better than being overly clever (at least in these days of really good JIT interpreters).  Here's my new string multiplication code:</p>

<pre>
String.prototype.times = function(n) {
    var s = this, total = "";
    while(n > 0) {
	if (n % 2 == 1) total += s;
	if (n == 1) break;
	s += s;
	n = n>>1;
    }
    return total;
};
</pre>

<p>By my <a href="http://www.davidflanagan.com/demos/multiply.html">simple benchmarks</a>, this implementation is significantly faster than using join(), even when only multiplying by 1 or 2.  I've tested it in Firefox 3.5, IE 8 and Safari 3.</p>]]>
        
    </content>
</entry>

<entry>
    <title>String Multiplication in JavaScript</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/08/string-multipli.html" />
    <id>tag:www.davidflanagan.com,2009://1.172</id>

    <published>2009-08-18T02:52:53Z</published>
    <updated>2009-08-18T03:17:33Z</updated>

    <summary>In Ruby, the &quot;*&quot; operator used with a string on the left and a number on the right does string repetition. &quot;Ruby&quot;*2 evaluates to &quot;RubyRuby&quot;, for example. This is only occasionally useful (when creating lines of hyphens for ASCII tables,...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>In Ruby, the "*" operator used with a string on the left and a number on the right does string repetition.  "Ruby"*2 evaluates to "RubyRuby", for example.  This is only occasionally useful (when creating lines of hyphens for ASCII tables, for example) but it seems kind of neat.  And it sure beats having to write a loop and concatenate n copies of a string one at a time--that just seems really inefficient.</p>

<p>I just realized that there is a clever way to implement string multiplication in JavaScript:</p>

<pre>
String.prototype.times = function(n) {
    return Array.prototype.join.call({length:n+1}, this);
};

<p>"js".times(5)   // => "jsjsjsjsjs"<br />
</pre></p>

<p>This method takes advantage of the behavior of the <code>Array.join()</code> method for arrays that have undefined elements.  But it doesn't even bother creating an array with n+1 undefined elements.  It fakes it out using and object with a length property and relies on the fact that <code>Array.prototype.join()</code> is defined generically.  Because this object isn't an array, we can't invoke <code>join()</code> directly, but have to go through the prototype and use <code>call()</code>.  Here's a simpler version that might be just as efficient:</p>

<pre>
String.prototype.times = function(n) { return (new Array(n+1)).join(this);};
</pre>

<p>When you call the Array() constructor with a single numeric argument, it just sets the length of the returned array, and doesn't actually create any elements for the array.</p>

<p>I've only tested these in Firefox.  I'm assuming that either is more efficient than anything that involves an actual loop, but I haven't run any benchmarks. </p>]]>
        
    </content>
</entry>

<entry>
    <title>Proposed coding convention for closures</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/05/proposed-coding-1.html" />
    <id>tag:www.davidflanagan.com,2009://1.171</id>

    <published>2009-05-15T19:35:55Z</published>
    <updated>2009-05-16T04:11:26Z</updated>

    <summary> By now, many of us have gotten used to using closures in JavaScript to define a scope that holds private variables and utility functions so that we don&apos;t have to put these in the global namespace. The idiomatic code...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
By now, many of us have gotten used to using closures in JavaScript to define a scope that holds private variables and utility functions so that we don't have to put these in the global namespace.  The idiomatic code looks like this:

<pre>
(function() {
      var private_var;    // Visible only inside this function
      function helper_function() { ... }
      
      // export an object or function to the global namespace
})();  // Invoke the outer function
</pre>

<p>
The outer function exists only to create a scope to hold our internal variables.  It has no name and is invoked exactly once, immediately after being defined.  The fact that this is a function expression (rather than a statement-like function declaration) means that we can invoke it immediately after defining it.  The parentheses before the function keyword and after the closing } are required because otherwise the JavaScript interpreter would think that this was a function declaration and would complain about the missing function name.  

<p>
That unusual opening parenthesis before "function" serves another important purpose in this idiom.  It alerts us to the fact that this function is being used idiomatically, that it exists solely to create a scope and that it is going to be invoked immediately.

<p>
So far, so good.  But I've finally gotten around to reading Douglas Crockford's 
<a href="http://www.amazon.com/gp/product/0596517742?ie=UTF8&tag=davidflanagancom&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596517742">JavaScript: The Good Parts</a><img src="http://www.assoc-amazon.com/e/ir?t=davidflanagancom&l=as2&o=1&a=0596517742" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> and it has made me think that an additional explicit naming convention would be helpful.  (As an aside, Crockford's short book is worth a read, though I find that I disagree with some of his coding conventions.  I'm tempted to write a review titled "JavaScript: The Good Parts: The Good Parts"...)

<p>
When the function keyword is the first token in a new JavaScript statement, the interpreter expects to see a function declaration, not a function expression.  That's why we needed the idiomatic parentheses in the code above.  But when the function keyword is used as part of an assignment or as an argument to some other function, those parentheses are not required.  Crockford's book includes code like this (page 37):

<pre>
var myObject = function() {
    var value = 0;

    return { // 7 lines of code omitted here
    };
}();
</pre>

<p>
When I first read the assignment statement it appears to me (despite the name of the variable) that it is a function value being assigned.  In fact, however, the function is merely there to establish a scope for private variables.  The function is invoked as soon as it is defined, and it is the return value of the function that is assigned.  The problem is that I don't realize this until I read all the way down to the end of the function.  Appendix E takes this to an extreme.  The code begins:

<pre>
var json_parse = function() {
</pre>

<p>
It looks like we're creating a function and assigning it to the variable json_parse.
But five pages later we see:

<pre>
}();
</pre>

<p>Now we realize that the value assigned to json_parse is not the function we thought it was, but the function returned by that function.

<p>Another example appears on page 40: 

<pre>
String.method('deentityify', function() {
   // 25 lines omitted
}());
</pre>

<p>It appears at first that we're passing a function as the second argument of the invocation of String.method.  It is not 'till we read all the way through this function that we realize that we're passing the result of invoking the function.

<p>So, how can this code be improved?  One way would be to use the idiomatic parentheses around function expressions that are going to be immediately invoked even when they are not necessary.  That would turn the code above into this:

<pre>
String.method('deentityify', (function() {
   // 25 lines omitted
})());
</pre>

<p>I think that would be helpful, but I think we can do better.  Function expressions are allowed to have names, and those names are only visible within the body of the function (allowing such a function to invoke itself recursively, for example).  So let's say that when we're going to define a function for the purpose of creating a scope we make that explicit by giving it a dummy name like "scope" or "closure" or "invocation".   This results in code like:

<pre>
var myObject = function scope() {
   // code omitted
}();

String.method('deentityify', function invocation() {
   // 25 lines omitted
}());
</pre>

<p>Your thoughts are welcome in the comments.  Has anyone else proposed a convention like this?  What's the best name to use for these functions?

<p><b>Update:</b> I suppose we could also simply adopt a comment-based convention:

<pre>
var myObject = /* return value of */ function () {
   // code omitted
}();

String.method('deentityify', /* result of */ function() {
   // 25 lines omitted
}());
</pre>

<p><b>Update 2:</b>  It turns out that Douglas Crockford is about 2 months ahead of me.  In March he updated <a href="http://jslint.com">jslint</a> to (optionally) issue warnings about immediate invocation of function expressions unless the entire invocation appears in parentheses, and also to warn if a function is parenthesized and is not immediately invoked.  So Crockford's convention looks like the following:

<pre>
var myObject = (function () {
   // code omitted
}());

String.method('deentityify', (function() {
   // 25 lines omitted
}()));
</pre>

<p>Note that Crockford wraps the invocation in parens, not just the function.  That is, he uses <tt>())</tt> at the end instead of (the more commonly used) <tt>)()</tt>.  He has said that he'll update his book to follow these conventions in the next printing.]]>
        
    </content>
</entry>

<entry>
    <title>New version of Jude, plus Java 1.5 server JVM bug</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/04/new-version-of.html" />
    <id>tag:www.davidflanagan.com,2009://1.169</id>

    <published>2009-04-27T18:25:14Z</published>
    <updated>2009-04-27T18:47:05Z</updated>

    <summary>I&apos;ve just released Jude version 1.07. This is a relatively minor bug-fix release. Thanks to B.L. for reporting the bugs and helping to isolate them. Interestingly, one of the bugs reported against the previous version was an ArrayIndexOutOfBoundsException at a...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="java" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've just released <a href="http://www.davidflanagan.com/Jude">Jude</a> version <a href="http://www.davidflanagan.com/Jude/Download">1.07</a>.  This is a relatively minor bug-fix release.  Thanks to B.L. for reporting the bugs and helping to isolate them.</p>

<p>Interestingly, one of the bugs reported against the previous version was an ArrayIndexOutOfBoundsException at a spot where such an exception really was not possible.  This had me really puzzled--I could not duplicate it.  But when I discovered that inserting debugging <tt>println()</tt> calls made it go away, I realized that this was a JVM problem and not my bug.  It turns out that in Java 5 (we tested u17 and u18) on Linux (at least) running with the -server option would cause this spurious exception. Running with -client (which is the default for most installations, I think) would not cause it. The crash never occurred at precisely the same spot in a run, leading me to think it was a GC bug.  Unfortunately, I've got no idea how to isolate a bug like this with a simple test case so that I can report it.</p>]]>
        
    </content>
</entry>

<entry>
    <title>New ECMAScript version numbering scheme</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/03/new-ecmascript.html" />
    <id>tag:www.davidflanagan.com,2009://1.168</id>

    <published>2009-03-30T22:53:00Z</published>
    <updated>2009-03-30T22:58:26Z</updated>

    <summary>Per a post today on the es-discuss mailing list, the next version of the JavaScript standard will be ECMAScript 5. This version was previously called ECMAScript 3.1, and is a relatively small and long-overdue update to the language. Version 4...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Per a post today on the es-discuss mailing list, the next version of the JavaScript standard will be ECMAScript 5.  This version was previously called ECMAScript 3.1, and is a relatively small and long-overdue update to the language.  Version 4 of the standard has been in the planning stages for 10 years or more, but those plans have been scrapped.  To avoid confusion, with those old plans, however, there will be no version 4 of the standard.  </p>]]>
        
    </content>
</entry>

<entry>
    <title>$SAFE is Proc-local</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2008/11/safe-is-proc-lo.html" />
    <id>tag:www.davidflanagan.com,2008://1.167</id>

    <published>2008-11-13T23:22:24Z</published>
    <updated>2008-11-14T00:04:31Z</updated>

    <summary> While researching Ruby&apos;s new-in-1.9 Object methods untrusted?, untrust, and trust, I discovered something I did not know about the $SAFE variable: in addition to being Thread-local, it is also Proc-local. Proc objects (both procs and lambdas) have their own...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="ruby" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
While researching Ruby's new-in-1.9 Object methods <tt>untrusted?</tt>, <tt>untrust</tt>, and <tt>trust</tt>, I discovered something I did not know about the <tt>$SAFE</tt> variable: in addition to being Thread-local, it is also Proc-local.  <tt>Proc</tt> objects (both procs and lambdas) have their own copy of <tt>$SAFE</tt>, and they run at whatever <tt>$SAFE</tt> level was in effect when the <tt>Proc</tt> was created not the safe level that is in effect when they are invoked.  This was <a href="http://redhanded.hobix.com/inspect/lambdaIsASafecracker.html">discussed three years ago over at _why's old blog</a>.
<p>
There is a corollary, however that was demonstrated but not discussed in a <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/18352">recent ruby-core post by Shugo Maeda</a>:
if you set <tt>$SAFE</tt> inside a proc or a lambda, that setting is local, and does not change the global safe level.   Googling for "safe_eval" implementations shows that everyone uses Thread.new to create a sandbox with a locally elevated safe level.  It turns out, however, that an ordinary lambda will also work.  (One can argue, however, that a thread gives extra safety because it can be monitored and killed to guard against runaway code that doesn't terminate.)
<p>
In any case, here is the method I defined to try this out.  Pass it a safe level (it defaults to 4) and a block of code, and it will execute the block at that level without altering the global safe level and without creating a new thread:
<p>
<pre>
# Execute a block at the specified safe level. Tested with Ruby 1.9 and 1.8.7
def safely(level = 4)
  sandbox = lambda do # Set up a sandbox 
    $SAFE = level     # Go to the specified safe level for this lambda only
    yield             # Invoke the block at that level
  end
  sandbox.call        # Invoke the sandbox without changing $SAFE globally
end

# Use this method like this. 
x = safely { eval('"untrusted code"') }
[x, x.tainted?, x.untrusted?]  # => ["untrusted code", true, true]
</pre>
<p>
I'm not convinced that this method is actually useful in practice, but I thought it was interesting, and it reminds me again how cool it is to be able to define methods that accept blocks and act like control statements.]]>
        
    </content>
</entry>

<entry>
    <title>Bending the Arc of History</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2008/11/bending-the-arc.html" />
    <id>tag:www.davidflanagan.com,2008://1.166</id>

    <published>2008-11-06T00:28:11Z</published>
    <updated>2008-11-06T00:43:02Z</updated>

    <summary> President-elect Obama sure writes and delivers a great speech! My favorite line from his victory speech last night: put their hands on the arc of history and bend it once more toward the hope of a better day. I...</summary>
    <author>
        <name>David</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
President-elect Obama sure writes and delivers a great speech!  My favorite line from his 
<a href="http://my.barackobama.com/page/community/post/stateupdates/gGx3Kc"> victory speech</a> last night:

<blockquote>
<p>
put their hands on the arc of history and bend it once more toward the hope of a better day.
</p> 
</blockquote>
<p>
I love the image of bending the arc of history.  Certainly appropriate to the occasion last night.  Let's hope that under the Obama administration we can continue to bend the arc of history toward (to pick one example) reduced CO2 emissions!]]>
        
    </content>
</entry>

</feed>
