Client-side web programming


(*note to photography subscribers: this is a photography and programming blog, if you only want to read articles on photography, subscribe to the photography-only feed)

While I prepare the next big article, here’s a useful tip for Flash and Flex programmers. ActionScript 3.0 is great, but has no Singletons.

Samuel Agesilas has a solution that successfully prevents subclasses from calling the constructor using super(), but it doesn’t prevent other code from creating new instances of a class with new

Therefore I present to you a crafty hack to make a constructor truly private: add a required argument to the constructor, which must be set to a secret value that is only known to the class:

class Singleton {
    private static var _instance:Singleton = null;

    // secret known only to this class
    private static const secret:Number = Math.random();

    /**
     * @private
     */
    public function Singleton(enforcer:Number) {
        if (enforcer != secret) {
            throw new Error("This class can't be instantiated directly");
        }
    }

    /**
     * Global single instance
     */
    public static function get instance():Singleton {
        if (_instance == null) {
            _instance = new Singleton(secret);
        }
        return _instance;
    }
}

This method also has the advantage that it is very fast, and offers a level of compiler protection: new Singleton() will fail at compile time. A user could make the compilation work by passing in, for example new Singleton(42), but there is a very high* chance of that failing at runtime.

Use this technique whenever a constructor should only be called from within a class, to save your users from the all too easy mistake of of creating a second instance of a singleton.

* Geeky aside: the change of guessing the result of Math.random() is 1 to 2^52 against, or 1/4,503,599,627,370,496. This is because 64 bit floating point numbers have a 52 bit mantissa.

Update: Grant Skinner has another way of doing the same thing. His is probably more elegant, but less amusing, and amusingness is a trait I value in language hacks. Also, his solution is not checked at compile time. Andrew Trice had a go too. His version requires an extra argument so provides compile time checking, but can be defeated by calling new Singleton(Singleton.getInstance). Thanks for the links shaun.

Update 2: Ho hum, Eric J Feminella has a solution that is better than mine, since it is properly checked at compile time, i.e. you can’t fool it by passing in any int, and falling back on runtime checking (though null would work). I still contend that my solution is more amusing though :o)

Sorry about the long delay between articles, I was busy getting married. A big thank you to the people who asked if I was going to write any more: I’m back in the game now.

When I built Animator.js, I got some flack for suggesting that inheritance is not a Good Thing. Keen to avoid a holy war I restated my position to ‘inheritance is often useful, but more often overused.’ Over the last few months I’ve been trying to figure out exactly when it should be used, and have concluded - at least for the kind of systems GUI developers build - never. There are better techniques that accomplish the same thing.

In this article I justify my dislike of inheritance as a prelude to my next article introducing an open source animation toolkit that is built without inheritance.

Read the article here.

Edit: Eric Herman wrote in with a link to a good article he wrote giving a more detailed example of the same problem from a Java point of view.

Edit 2: OK, I couldn’t make this stuff up. This is a verbatim quote from the Java API documentation for the Properties class that reads configuration from a file:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a “compromised” Properties object that contains a non-String key or value, the call will fail.

This is what inheritance does to your system! In all fairness, the Java API team introduced the generic collections API to get around this kind of problem, but it’s still funny.

If ever a feature of JavaScript was considered harmful, it’s eval(). It’s so commonly abused that if I’m interviewing a JS web developer, I usually ask something along the lines of “what is eval(), and why shouldn’t you use it”. It’s so commonly abused that Yahoo JavaScript architect Douglas Cronkford considers it “evil”, and his JavaScript style checker JSLint reports use of it as an error.

Specifically, he says:

The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes useful for parsing JSON text, but in virtually all other cases it indicates the presences of extremely bad coding. The eval function is the most misused feature of JavaScript.

Well I’m tired of my favourite function being badmouthed just because some people can’t program properly. In this article I show how to use eval to generate optimised code based on information only available at run time. The resulting code is 5 times faster than the non-generated version.

I’m preparing another (hopefully) useful full length article, but in the mean time I want to share with you a trick for getting a world-class debugger for free in IE.

JavaScript debugging in Visual Web Developer ExpressSome background: users of Visual Studio have long known that it comes with an awesome debugger, probably the best JavaScript debugger there is (though Firebug is catching up fast). Whenever you get a JavaScript error, Visual Studio can connect to the Internet Explorer process and start debugging. You can pause the execution of the code, rewind and fast-forward execution, modify data held in variables and get notified when specific variables change in value. Once you’re used to it, coding without a debugger makes you feel like a blind man in a dark room looking for a black cat that isn’t there*.

The only problem is that it costs upwards of £500. Microsoft have released an excellent free edition of Visual Studio for web development called Visual Web Developer, but among the features reserved for the professional edition is the ability to connect to a process. Hence when you get a JavaScript error in a web page, VWD won’t appear in the list of possible debuggers.

The work-around is to get VWD to launch IE for you, so that it owns the process and doesn’t have to explicitly connect to it:

1 Internet Explorer Options First enable debugging in IE: go to Tools > Internet Options > Advanced, and make sure “Disable Script Debugging (Internet Explorer)” is unchecked and “Display a notification about every script error” is checked.
2   Then Download and install VWD
3 Adding a new empty website in Visual Web Developer Create a new empty website
4 Start Debugging

Click the “Start Debugging” button. You will be prompted to enable debugging for this website - do so. VWD will then launch IE in debugging mode.Since your website is empty you will see a 404; ignore it and navigate to the actual page or website you want to debug.

A tip from Fraser in the comments below: If you like, you can create a home page for the new site, and add this code to the head section:  <meta http-equiv=”refresh” content=”0;url=http://yoursite.com”>. This will redirect you automatically to your chosen site.

5 JavaScript debugging in Visual Web Developer Express Any script errors will cause IE to pause execution and transfer control to VWD.The screenshot to the left shows me changing the value of a variable as the script is paused.

If any Firefox users have probelms getting VWD to launch IE, see James Wiltshire’s comment below.
A few debugging tips:

  • Learn these shortcuts: Step Over (F10) executes the current line of code and moves to the next one. If the current line of code contains a function call, Step Into (F11) moves the debugger into that function call. Step Out (Shift+F11) executes the rest of the current function and pauses again after it returns. Continue (F5) resumes the script until the next error or breakpoint.
  • Debugging is easier if you write code with one function call per line, so that the debugger knows which function you want to step in to.
  • You can type any expression in the Watch window, and when its value changes it will turn red.
  • If you want to open the debugger when there is no error, click in the left-hand margin to set a break point or place the ‘debugger’ keyword in your code (this works in Firebug too).
  • The Script Explorer window is an extremely useful list of open JavaScript and HTML files that you can use to find code in order to set a breakpoint. It is not shown by default but you can enable it in Debug > Windows > Script Explorer.

Happy coding!

* joke stolen from Rowan Atkinson

I’ve released an update to Animator.js.

Highlights are:

  • You can now specify the start and end states of an animation using CSS class names: no more style information in your JavaScript code! IMHO this makes it twice as useful as the last version.
  • AnimatorChain class makes it easy to chain several animations together (thanks Lachlan Donald and Colin Snover for the idea)
  • No more dependency on Prototype.js, so users of other toolkits can use it freely.
  • Useful new transitions: elastic, bouncy and Attack Decay Sustain Release.
  • Bug fixes - styles can now have negative or fractional values

Thanks to all the people who wrote to me with suggestions and example of work you’ve done with Animator, keep them coming!

I was pleasantly surprised by all the good feedback I got for Animator.js since Ajaxian linked to the article.

The most requested feature was “Can I port it to MochiKit/jQuery/Dojo/mootools”. Which got me thinking – Animator.js is built on Prototype because I didn’t want to rewrite code for function delegation and element manipulation myself, but it doesn’t use any of Prototype’s advanced functionality. I could remove the dependency on prototype quite easily and then it would work with any toolkit. I estimate this would add about 1K to the file size.

Having a class that can be used in any toolkit would be much better than a number of independently maintained forks.

Two questions:

  1. What changes should I make to ensure that it can plug in to your favourite toolkit?
  2. If someone can make a product usable for more people by re-implementing basic functionality again, is it worth it? Or is the world standardising on Prototype to do all that for them?

I’ll be making another release in a couple of weeks so let me know your thoughts, and any other feature requests.