After several years hiatus from the raw Enterprise Java space (I’ve been doing lots of Grails coding), I’ve been wading back into some client work around native EE6 (porting a Grails app to EE6 was the reason for my onboard, but that’s the subject of a different post).

Why Guava?

On the way back into the EE landscape, I’ve been refreshing myself with what’s hip and happening in the space. Several of my mates pointed me at Google Guava as a nice way of working around null-handling, collection-immutability, and reducing boilderplate.

I’m basically using it as a modern Apache Commons, but it’s a lot more than that. What is immediately apparent is that there is a lot of consistency across the library, so someone has obviously given themselves to make this amazing. And many of these constructs will have an equivalent in Java 8, so you can start “living in the future” today on your current JDK.

A Better ToString()

To get started, one of the simple things I was looking for was just a nicer way to do “ToString()”. I’ve always been fond of Groovy’s Object.dump() method, and was chasing a way to output a similarly consistent output on my own stuff. Back in the day I used to use Commons ToStringBuilder with the ReflectionToString gear and was keen to see Guava’s approach.

Here’s the typical idiom using my Account object as a sample (it’s all nullsafe as you’d expect):

@Override
public String toString() {

        return Objects.toStringHelper(this)
                .add("name", username)
                .add("email", email)
                .add("created", dateCreated)
                .add("lastLogon", lastLogin)
                .toString();
}

And you’re in business. Time to have a look at the output:

@Test
public void aMuchNicerToString() {
        Account account = new Account("glen", "password", "glen@bytecode.com.au");
        String expected = "Account{name=glen, email=glen@bytecode.com.au, created=null, lastLogon=null}";
        assertEquals(expected, account.toString());
}

Sweet and consistent.

I’m a bit rusty on all this, but it’s been quite fun diving deep into mainstream Java and catching up on what’s happening.   You can go grab all the code for this series in a Github project.

Given I know just about nothing about Guava, my pretense has no boundaries, so feel free to correct me along the way if you know about this stuff.

Have fun!