Naming the Unnamed

Many languages support the declaration of entities in a nested scope. Java supports inner classes. C++ supports nested classes. JavaScript lets you declare functions in just about any scope.

Several languages, including Java and JavaScript, allow you to declare entities anonymously. In Java, you create anonymous inner classes, commonly for simple or one-off callback classes like Swing event handlers (see Listing 9-8). JavaScript developers pervasively use anonymous functions as callbacks (Listing 9-9), for immediate execution, and to wrap function declarations to freeze closures.

Listing 9-8: Example of an anonymous inner class as a Java Swing event listener

button.addActionListener(  new ActionListener() ...

Get Quality Code: Software Testing Principles, Practices, and Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.