Conciseness challenge

This post berates Java for being overly verbose compared to Scala. At times (most of the time ?) this is justified, however two examples in particular stand out, which I could not resist try and improve upon:

1. Loop Syntax

The “long” version from the post above:

       ArrayList<Integer> x = new ArrayList<Integer>(3);

        for (Integer y:x)
            if ( y > 2 )

…this can be easily reduced to a couple of lines (using Guava)

 for(Integer y: newArrayList(10,11,12))  {
        if ( y > 2 ) System.out.println(y);

2. Checking for argument correctness in a constructor.

The original version:

class Person
    private String name;
    private int age;

    public Person(String n, int a)
        if ( age < 18 ) {
            throw new IllegalArgumentException();
        name = n;
        age = a;

Using the Preconditions api from the Guava libraries and the AllArgsConstructor annotation from project Lombok this turns into a slightly more compact version:

class Person2
    private  String name;
    private  int age;

    static Person aPerson(String name, int age){
       return new Person2(name,age);

Still not quite as terse as the equivalent code in Scala, but gets to the point whilst remaining easily readable.


Leave a Reply

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

You are commenting using your 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