Java 7 get/set syntax shortcuts

December 27, 2006

Now that Java 6 has been released, people are starting to talk more about the future of the language. I noticed Kirk Pepperdine’s comments in Java 7.0 language feature considered harmful:

“I’ve just watched the Danny Corward presentation at the Prague JUG on what could be coming in the JSE 7.0. In that presentation he demonstrated the “->” operator. The purpose of the operator is to provide a short hand notatino for properties. The syntax that we would normally use is;

a.setFoo( b->getFoo());

With the “->” operator we would see;

a->foo = b->foo;

How we’d currrently coding this is;

a.foo = b.foo where foo would have to be more visiable than private.”

He goes on to comment on how this violates OO data encapsulation principles and I agree with his arguments about these principles themselves, but I don’t see what the problem with syntactic sugar for very standard method calls is (I am assuming this proposed syntax is, as he suggests, just syntactic sugar for getFoo() and setFoo(x) and that the resulting bytecode is the same). This is just a compiler facilitating something already possible, like using:

 String[] x = {"one", "two"}; 

instead of:

 String[] x = new String[2]; x[0] = "one"; x[1] = "two"; 

As someone who likes Python a lot, it’s a natural thing for me to see “a.foo = x” and understand that a set method could have been executed. You can use “__getattr__” and “__setattr__” to override member access/mutation via instance.property syntax. This can be employed to do useful things behind the scenes while maintaining simple, legible code (such as in SQLObject).

If only it weren’t far too late for Java to eliminate the ability to do direct instance.property access altogether and have that mean get/set instead :-).