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

Let’s quickly see some of the sample usages

Checking for null values

Let’s see the simple API

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

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

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 *