Skip to main content

Java 7 - Extension methods

Posted by forax on November 29, 2007 at 3:15 AM PST

Peter and
blog about extension methods.

Why i hate (yes hate) use-site extension ?

What i love (yes love) with Java is the fact that i
can take a look to a screen over one of my student
shoulder and be able to say is the snippet i see
is correct or not.

With the use-site extension
proposed by Neal,
the behavior of a code depends on some static imports
that are located in the beginning of the file.
So you can't understand a code without browsing
the entire file.

Demonstration. Do you understand this code ?

String text=...
for(int i=0;i<text.size();i++) {

Hum, i have forget to say that the begining of
the file contains that declaration:
import static Strings. and that
the class Strings is defined like that:

 public class Strings {
   public static int size(String s) {
     return s.trim().length();

I'am sure i will hate that.

It will remember me the the mess of C++ member functions:
"where is the f***ing def of this method".

Furthermore, import static has already some limitations,
the code below doesn't compile. This case is currently
rare but with extension methods it will be more frequent.

  import static java.util.Arrays.*;

  public class StaticImport {
    public static void main(String[] args) {

Why i prefer declaration-site extension methods ?

It's definitely a good property of a language
to be able to understand
a code that deals with some java.util.Lists,
just by knowing the declaration of this type.
If i don't know how to use it, i can just to
browse its code.
After that, because i have a good brain storage device,
i will be able to understand ALL codes that deals
with java.util.List.

Another proposed syntax

I think there is some problems with the
syntax proposed by Peter.

  package java.util;
  public interface List     
Related Topics >>