Norvig’s literal instance hack for Java


Because not enough Java programmers know about Norvig’s cute trick.

Consider java.awt.Polygon. It’s a nice enough class, but its constructors make it awkward to use directly in a call to java.awt.Graphics.fillPolygon.

Norvig points out that you can create an anonymous class and write an initialiser for it. Like this: «new Polygon() {{addPoint(0,0); addPoint(100,50); addPoint(100,-50);}}». That’s an expression. That means that if we’re drawing on a java.awt.Graphics object g we can go «g.fillPolygon(new Polygon() {{addPoint(0,0); addPoint(100,50); addPoint(100,-50);}});». It saves us from having to declare a very temporary Polygon variable.

Norvig’s example is even more compelling. You can create anonymous literal Vectors just as easily as literal arrays: «new Vector(3) {{add(“one”); add(“two”); add(“three”)}}».

Of course the double curly braces makes it look a bit scary, probably even to experienced Java programmers. But I think I like that.

Don’t even think about doing this in JME. The extra inner class costs at least 400 bytes.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: