Brian Slesinsky's Weblog

Saturday, 06 May 2006

Responses on Auto Variables

It's been over a month since my previous entry on adding auto variables to Java. Unlike most of my blog posts, I actually got a few responses, so at least I wrote something interesting. But surprisingly, most responses were negative.

My bug report to Sun seems to have gone to /dev/null, so you can't vote on this. (That's not surprising for Sun.)

The IntelliJ folks aren't interested in being ahead of the language spec (not surprising), and also pointed out something I had forgotten: there is already type inference in the other direction. For example:

  List<Integer> list = Collections.emptyList();

In this case, you couldn't leave out the type because it would be ambiguous.

I don't think that's a fatal flaw since there are plenty of unambigious cases. Basically any situation where getFoo().doBar() is allowed, you should also be able to write:

  final foo = getFoo();

I was surprised that some Java programmers (including one famous one at work) don't see much advantage to it and are afraid it would make Java code less clear. With all the scripting dynamically-typed language advocates loudly trumpeting how much easier their languages are to use because you don't have to write type definitions everywhere like you do in cumbersome, excessively verbose languages like Java, I thought the advantage of a conservative change towards better ease-of-use that doesn't break type-safety would be obvious. And of course you can still write out the type when it adds clarity.

One correspondent seemed confused and thought this would remove type safety. While it's true that there would be fewer compiler errors in a program that uses local type inference, I claim that the errors that this approach gets rid of are unimportant. In the code above, we don't really care what getFoo() returns so long as we can prove at compile time that it has a doBar() method. A type error here is simply an annoyance, and it's a good thing that a refactoring that changes getFoo's return type will require fewer code changes. It's a simple form of duck-typing at the local level.

Also, we do this aready. Whenever you write an expression such as getFoo().doBar(), no type is declared for the intermediate value. Nobody seems concerned about this, so why get upset about local variables?

But in any case, I think I got an answer to my question: it's not happening because many Java programmers are surprisingly conservative.