Thursday, November 22, 2007

Followup to Feature request for JDK7: delegation

A followup to Feature request for JDK7: delegation.

In the comments to my post requesting better IOC support in JDK7 Sam asks, "The keyword *is* needed... what if the delegate is editing the behaviour of one of the methods? Perhaps to do some logging. You can't do that with the original code." For some context, he refers to code like this:

class Scout implements Camper {
    public void camp() { ... }
}

class BoyScout implements Camper {
    BoyScout(Scout scout) {
        this = scout;
    }

    public void camp() {
        callHomeFirst();
        ??? // How to forward to delegate?
    }
}

I've thought about this for a bit and I think I would go with this:

public void camp() {
    callHomeFirst();
    Camper.this.camp();
}

Why?

I have several reasons:

  1. It introduces no new syntax or keywords.
  2. It does not collide with any existing use.
  3. It is reminiscent of inner class access to their outer containing class this.

My first impulse was for some kind of casting:

((Camper) this).camp();

But this is just ugly! Then using the JLS calls qualified this occurred to me, this:

Camper.this.camp();