Thursday, October 30, 2008

Capital-This

Java ...

Update: Matthias Ernst proposes an even better solution that I've thought of as well - it would accomplish the same thing as Capital-This, but without requiring changing the code. Anything that returns void would "cascade". This would be awesome

fill the void. An invocation expression of a method with return type void could be treated as if returning the receiver, enabling cascaded sends. Bean b = new Bean().setA(a).setB(b);



I'm always writing methods that return "this" so that calls can be chained.

class Blah {
Blah setText(String stuff) {}
}
...
Blah blah = new Blah().setText( "stuff" ).setReps( 2 );

Which works fine for a single class. But java is supposed to be OO - as soon as I extend Blah, I run into trouble when I:
public class Foo extends Blah { ... }
Foo foo = new Foo().setText( "again" ).fooInit( 0 );
setText returns a Blah, not a Foo and I'm left with an error. To overcome this problem, I have to override setText, and any other methods that follow the same convention, in every subclass. Not practical, and not very OO - instead we tend to write:
Foo foo = new Foo();
foo.setText( "again" );
foo.fooInit( 0 );
which works, but isn't as elegant. Eg, it sucks with with matrix algebra, b1 is much clearer than b2:
// calculate 1-a1*a2
Matrix b1 = new Matrix(a1.size()).set(1).sub(a1.mult(a2));
Matrix b2 = new FloatMatrix(a1.size()), tmp = a1.mult( a2 );
b2.set(1);
b2.sub( tmp );
Java needs a "This" return type that is equivelent to
class Blah { This myMethod() { return this; }
class Foo extends Blah {
Foo myMethod() { super.myMethod(); return this; }
}

"This" makes so much sense to me, and makes the language more "Java". Am i missing something ? Why isn't it implemented ? Java needs Capital-This.

No comments: