Guava null checkers

30 08 2015

A short demo introducing methods of handling null objects, null checks and null comparisons in guava. These guava methods will reduce the amount of ifs, NPEs and try-catch blocks.

Here is what you can do:

Null safe equality check

// --------- null-safe equality check ---------
String nullString = null;
String nameString = "Jack";

Objects.equal(nullString, nameString);  //returns false
nullString.equals(nameString);          //throws NPE
// ---------

Get default value if the first value was null

// --------- use the default value if previous arguments were null ---------
String login = "userLogin";
String name = MoreObjects.firstNonNull(methodThatMayReturnNull(), login);

//is the same as Java's:
name = methodThatMayReturnNull();
if(name == null)
    name = login;
// ---------

Check if argument is null

// --------- Argument check against null ---------
String nullArgument = null;
Preconditions.checkNotNull(nullArgument, "Argument was null!");   //throws NPE if argument is null
// ---------

Demo source Code

Download source code with these examples from my github:



Give Your feedback:

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

%d bloggers like this: