Java’s missing features
The following is a list of the language features I miss most when programming Java:
- Closures: are useful for implementing abstractions that involve behavior. Smalltalk provides ample proof that functions and object-orientation go together well. Instead of giving Java functions as objects, its creators decided to support the encapsulation of behavior via inner classes. At long last, it looks like Java 7 will have closures. They are essentially functions with built-in compatibility with single-method interfaces. Not perfect, but certainly very useful.
- Modules: are also coming to Java 7. Reinier Zwitserloot has a nice write-up of the rationale and current state of Jigsaw, Java’s module system. It is interesting that one requirement was that module have to cross-cut packages so that the core of Java can be properly modularized.
- Generators: let one repeatedly invoke a method. The method does not return a value, it yields it. A yielded value is passed to the caller in the same manner as with a return statement. But, the next time the method is invoked, execution continues after the last yield. Thus, a yield suspends method execution, and an invocation resumes it. This helps whenever data has to be computed lazily, on demand and in a piecemeal fashion: (The beginning of) an infinite list can be iterated over by writing a generator with an infinite loop. Tree iterators become trivial to write; one uses a generator and recursion. And so on... Astonishingly, generators are already in an experimental version of the JVM.
- Mix-ins: are class fragments that can be added to (mixed in) any given class, while defining it. The effect is similar to multiple inheritance, but results in a chain of classes (and not a tree, as with true multiple inheritance). Mix-ins are also sometimes called abstract subclasses, because they are classes whose superclass is left to be filled in. While it doesn’t look like mix-ins will be added to Java anytime soon, they could be simulated by tools as interfaces with implementations: If one attaches method implementations to special mix-in interfaces, those implementations could be automatically added to classes implementing such interfaces. While the compiled code will contain redundancies, the source code won’t and subtyping will work as expected. The attaching could be done by letting an annotation refer to a class.
- Post-hoc interfaces: Wouldn’t it be nice if one could let a class implement an interface after it has already been defined? After all, one can add new leaves to the inheritance tree, why not new inner nodes? This would give one many of the benefits of duck typing, while keeping compile-time checking.
While other features (such as multiple dispatch and better code browsing) would be nice to have, the above list contains my most urgent wishes for Java.