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
1 2 |
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
1 2 3 4 5 |
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
1 2 3 4 5 |
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
1 2 3 4 5 |
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.