Java Literally Sucks

May 4th, 2008

I use Java at my day job and I find it frustratingly verbose and confining. One thing that particularly bothers me is that I can’t easily represent literals.

Java adopted C’s convention for arrays:

    int[] x = {1,2,3}

which work fine if I want to use arrays; but I rarely use arrays because I like OOP and I usually want to do things with my data structures like call methods on them. So, I typically use a list which I could declare like this:

    List l = new ArrayList();
    l.add(1);
    l.add(2);
    l.add(3);

… but I don’t do that because I don’t like warning about not using generics properly so I usually declare the list in this even more verbose way:

    List<Integer> l = new ArrayList<Integer>();
    l.add(1);
    l.add(2);
    l.add(3);

The problem with both of these alternatives is that you really can’t “see” a list. You just see an allocation of a list container followed by three method calls. This really obscures the data structure in unnecessary logic.

Sometimes, in an effort to make my data structures less obscure, i create a list like this:

    List<Integer> l = Arrays.asList(new Integer[]{1,2,3});

Of course, this isn’t really a good idea because that list is immutable but it looks like it’s mutable which is kind of scary and weird to anyone who might expect this list to support operations like ‘add’ or ‘remove’ defined in the List interface.

To get around that problem, I’ve seen code that looks like this:

    List<Integer> l = new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3}));

which is, well, ridiculously awful.

This problem only gets worse when I want to do something outrageous like define a map for which I have no primitive like an array to help me out. This leads to a long series of put() invocations which makes me a little nauseated.

The fundamental problem is that Java has no literal representation for basic data structures. I’d argue that this deficiency led to the proliferation of XML in Java projects for defining data. I can’t think of another language whose users get so much pleasure out of something like Spring. Ruby users wouldn’t understand why you’d want to model parts of your application in a markup language: why not just use Ruby?

Comments are closed.