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);
        x.add(10);
        x.add(11);
        x.add(12);

        for (Integer y:x)
        {
            if ( y > 2 )
                System.out.println(y);
        }

…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:

@AllArgsConstructor
class Person2
{
    private  String name;
    private  int age;

    static Person aPerson(String name, int age){
       checkArgument(age>=18);
       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.

Advertisements

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