Using Google Guava Preconditions to validate Arguments

Validating method input arguments is a need for all API’s and we need to write the glue code every time we do validations. In a nutshell, the validation finally results into a boolean result that we take some action on.
Google Guava provides a nice way of validating the parameters in simple and concise way.

Note: Guava Preconditions throw runtime exceptions, so be ready to handle that.

Let’s see in simple words how do we validate

if (argument does not satisfy the condition)
   throw Some runtime exception 

Let’s quickly see some of the sample usages

Checking for null values

Let’s see the simple API

public static BufferedReader newBufferedReader (String fileName) throws IOException {
    Preconditions.checkNotNull(fileName);

    return new BufferedReader(new FileReader(fileName));
  }

Here in the API, we need to check that the filename should not be null, we use the checkNotNull API. If the filename is null, we shall get a NullPointerException.

Checking for other conditions

Let’s see a modified version of the check

public static BufferedReader newBufferedReader (String fileName) throws IOException {
    Preconditions.checkArgument(fileName != null && fileName.length() > 3);

    return new BufferedReader(new FileReader(fileName));
  }

Here we want to ensure that fileName is not null and has a min length of 3. You can add custom conditions as well.

Specifying custom error message

It’s always beneficial to add custom messages, to help debug and display error’s. Let’s modify the code above to display a user friendly message

public static BufferedReader newBufferedReader (String fileName) throws IOException {
    Preconditions.checkArgument(fileName != null && fileName.length() > 3, "File Name must have atleast 3 characterss");

    return new BufferedReader(new FileReader(fileName));
  }

We just use the API that expects another parameters, which shall be the message that needs to be used while throwing the Exception.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.