Variable Declarations
By Adrian Sutton
Jef Atwood has discovered the implicit variable type declaration in C#:
BufferedReader br = new BufferedReader (new FileReader(name));
Who came up with this stuff?
Is there really any doubt what type of the variable br is? Does it help anyone, ever, to have another BufferedReader on the front of that line? This has bothered me for years, but it was an itch I just couldn’t scratch. Until now.
Actually, there is a question about the type of br – it could be a BufferedReader or it could be any superclass of BufferedReader and sometimes that distinction is important. The most common example of this is in the collections API:
Map data = new HashMap();
Why not just call it a Map? Well let’s say you later want the map to be sorted, then it simply becomes:
Map data = new TreeMap();
And none of your other code needs to change. You’re guaranteed to not be using any HashMap specific methods because the compiler won’t let you and it’s quite clear that the intent is to work with a Map instead of specifically a HashMap. Saving a few extra characters really doesn’t give any benefit for either reading or writing.
What I find most fascinating about this, is that the example touches on the most verbose, confusing and frustrating (yet powerful) part of writing in Java – the IO library, and then complains about the type system. Here’s the real problem in that line of code:
new BufferedReader(new FileReader(name));
Do you have any idea how many people forget to wrap the FileReader in a BufferedReader and destroy the performance of IO (and then blame Java)? Why isn’t that something simple like:
Reader reader = new File(name).read();
Call the method name wantever you want and there’s a bunch of variants on this, but just provide a single method that does what the programmer almost always wants to do. If unbuffered, serial access to a file is ever desirable (when???) then provide an additional method that takes a boolean to let you turn off buffering but just make it simple.
Why people are obsessed with type systems as the harbinger of productivity is just beyond me – it’s the design of the libraries stupid! That’s why PHP feels so messy to write. That’s why Java feels so verbose to write. That’s why ruby feels so easy to write - it provides so many of these really handy shortcuts. No amount of syntactic sugar or changes to the type system is going to change that, because most of your code is dealing with the libraries, not the syntax of the language.