Thursday, August 05, 2010

Java verbosity again

(Repost of a comment I made somewhere on the topic of the verbosity of Java, and particularly its APIs)

The Reflection API is a fairly shocking example of the needless verbosity of Java. And I would consider the official API to be part of Java.

Here's a simplistic example in Java and Ruby, replacing characters in a string ("putty" => "puppy") first directly and then via reflective invocation:

// Java
String s = "putty";
System.out.println(s.replace('t', 'p'));
try {
Class c = s.getClass();
Method m = c.getMethod("replace", char.class, char.class);
System.out.println(m.invoke(s, 't', 'p'));
} catch (Exception e) {

# Ruby
s = "putty"
puts s.gsub("t", "p")
puts s.send("gsub", "t", "p")

This kind of verbosity is prevalent in Java's standard libraries, particularly when (anonymous) inner classes are involved. At the moment I'm struggling with "doPrivileged" blocks in some Java code which deals with sandboxing, and it is syntactically very unpleasant.

Ok, we could chain the Java calls together and knock some lines off, but it's still not nice:
try {
System.out.println(s.getClass().getMethod("replace", char.class, char.class).invoke(s, 't', 'p'));
} catch (Exception e) {


  1. I think it's a problem with OOP in general. You spend as much time on the object-oriented "plumbing" as you do solving the problem you want to solve.

  2. Hi Scientician,

    Perhaps OO languages have been historically more prone to this, especially the statically-typed ones, but note that Ruby is more object-oriented than Java, and is far more concise and readable in these examples.

    It's particularly bad in Java's case when you want to simulate first-class functions - the usual approach is to create an anonymous inner subclass of some expected interface, implementing a named method to be called. Then you have to go and make any closure variables final.

    The result ends up with, as you say, more boilerplate plumbing than the actual meat code for what you wanted to do.