Crockford’s JSDev: switching off privacy for testing

[2012-01-05] dev, javascript, jslang, jstools
(Ad, please don’t block)

Today, Douglas Crockford introduced a new project: JSDev. It solves a challenge with privacy: On one hand, you don’t want the outside world to have access to private functionality. On the other hand, you want to test it, via external unit tests.

How it works. You put development-only code into comments and start those comments with tags that indicate what the code is for. For example:

    function Account(password) {
        // private function
        function isValid(pwd) {
            return pwd === password
        /*testable this.isValid = isValid; */
Here, testable is a tag indicating that the following JavaScript code makes private code testable. After the tag, the actual development-only JavaScript code starts. It makes isValid() available as a public method. After you have run the development version of the above code, a unit test can work with new Account().isValid().

Development time. You use JSDev to produce the development-time variant of the code. Quoting Crockford:

You give it a list of the tags you want activated. It reads stdin, looking for those tags, and produces on stdout the activated development-mode program.
In the above case, you would execute the following Unix command:
    cat src/account.js | JSDev testable > srcdev/account.js
Deployment time. Any minification you apply to the code will remove the JSDev comments and thus prevent that the development-only code wastes space.

Other uses. Obviously this technique has other uses, for any kind of development-only code: logging, performance tracking, etc.

Most popular (last 30 days)