Java’s Verbosity: It’s Not Funny Anymore

Let’s say you have a Map-compatible object in Java, or a dict-like object in Python.

You know (or assume) that it has just one key/value pair in it. You want to assign the items to attributes of a class.

Python:

(outRow.key, outRow.value), = res.iteritems()

Java:

Map.Entry kv = res.values().toArray()[0];
outRow.key = kv.key;
outRow.value = kv.value;

It’s not really the two extra lines, though that’s also annoying as hell. It’s the “.values().toArray()[0]” replacing “.iteritems()” and a trailing comma on the other side of the assignment.

Note:

In Python, Guido viewed it as *too verbose*, and so in Python 3K, it’s just .items(), without the iter. The Java thing is frustrating because it is actually *cooler* than Python (.values() is a view, just like Python 3K has and Python doesn’t) but so much less comfortable.

Advertisements

3 Responses to Java’s Verbosity: It’s Not Funny Anymore

  1. Tuure Laurinolli says:

    How about outRow.key = map.keys().iterator().next(); outRow.value = map.values().iterator().next()?

  2. Adi Stav says:

    But your Python code above also verifies that the dict has only one item. In either your Java code or Tuure’s, you need to add a check and raise the appropriate exception, or else change the Python code to
    outRow.key, outRow.value = res.iteritems()[0]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: