Wednesday, December 12, 2007

Extension Methods

A new feature for Java 7?

Once an API has been published, you can't add methods to it without breaking backward compatibility. You can use abstract classes instead of interfaces, and only add concrete methods in the future. Unfortunately, that limits you to single inheritance.

One way API designers work around this limitation is to add new functionality to an interface by writing static utility functions. For example, java.util.Collection.sort acts as an extension of java.util.List. But such methods are less convenient to use, and code written using them is more difficult to read.

Extension methods enable programmers to provide additional methods that clients of an interface can elect use as if they are members of the interface. The simplest version of this feature that I advocate would be to enable statically-imported methods to be used as if members of their first argument type. For example:

    import static java.util.Collections.sort;
List<String> list = ...;

Closures Prototype Update and Extension Methods
Extension Methods and Chained Invocations

Traits have been suggested as an alternative:

Traits for Java

No comments: