Guava Preconditions Example

0

Guava provides some basic utility methods that check the correctness of parameters passed to method or a constructor.

These methods are grouped in a utility class called Preconditions.

Each method has three overloaded versions. The first one with just one parameter, mostly an expression that returns a boolean. The second one with an extra Object argument, Object.toString(), which will be used as the exception’s error message. The third version is more generic as it also allows a message template and an array of object arguments to replace the % indicators.

Let’s look into a simple example. If one wants to validate port number to make sure it is > than 0, one can use Precondition.checkArgument().

public static void validatePort(int port) {
    checkArgument(port >= 0);
}

The methods available in Preconditions are:

  1. checkArgument() – Ensures that the expression passed in is true else throws an unchecked exception.
  2. checkElementIndex() – Ensures that index specified is a valid element in an array. Index can be any value >=0 and < size.
  3. checkPositionIndex() – Ensures that index specifies a valid position in an array. Index can be any value >=0 and <= size.
  4. checkNotNull() – Ensures that the object passed in is not null
  5. checkState() – Ensures the expression passed in, involving the state of the calling instance, is true.

Let’s now look into a full fledged example.
In our example, TestBean contains methods which in turn delegate calls to Preconditions class.

TestBean:

package com.javarticles.guava;

import static com.google.common.base.Preconditions.*;

public class TestBean {

    public static void verifyArgumentCount(int[] args) {
        checkArgument(args.length > 2, "Arguments must be > 2");
    }    
    
    public static void validatePort(int port) {
        checkArgument(port >= 0);
    }    

    public static int validateElementIndexAndGetValue(int[] array, int index) {
        checkElementIndex(index, array.length);
        return array[index];
    }
    
    public static int validatePosIndexAndGetValue(int[] array, int pos) {
        checkPositionIndex(pos, array.length);
        return array[pos -1];
    }

    public static int checkNullAndReturnSum(Integer a1, Integer a2) {
        checkNotNull(a1, "a1 is null!");
        checkNotNull(a2, "a2 is null!");
        return a1 + a2;
    }

    public static void isServiceRunning(ServiceState serviceState) {
        checkState(serviceState == ServiceState.RUNNING, "Service is not running!");
    }
    
    enum ServiceState {
        STARTING,
        RUNNING,
        STOPPED
    }
}

We will now call methods in TestBean with different set of values.

PreconditionsExample:

package com.javarticles.guava;

import com.javarticles.guava.TestBean.ServiceState;

public class PreconditionsExample {
    public static void main(String[] args) {
        TestBean.verifyArgumentCount(new int[]{1, 2, 3});
        try {
            TestBean.verifyArgumentCount(new int[]{1, 2});
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
        TestBean.validatePort(4567);
        try {
            TestBean.validatePort(-1);
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
        System.out.println("Element at 2: " + TestBean.validateElementIndexAndGetValue(new int[]{1, 2, 3}, 2));
        try {
            TestBean.validateElementIndexAndGetValue(new int[]{1, 2, 3}, 3);
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e);
        }
        System.out.println("Element at position 3: " + TestBean.validatePosIndexAndGetValue(new int[]{1, 2, 3}, 3));
        try {
            TestBean.validatePosIndexAndGetValue(new int[]{1, 2, 3}, 4);
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e);
        }
        TestBean.checkNullAndReturnSum(2, 3);
        try {
            TestBean.checkNullAndReturnSum(null, 2);
        } catch (NullPointerException e) {
            System.out.println(e);
        }
        TestBean.isServiceRunning(ServiceState.RUNNING);
        try {
            TestBean.isServiceRunning(ServiceState.STARTING);
        } catch (IllegalStateException e) {
            System.out.println(e);
        }
    }
}

Output:

java.lang.IllegalArgumentException: Arguments must be > 2
java.lang.IllegalArgumentException
Element at 2: 3
java.lang.IndexOutOfBoundsException: index (3) must be less than size (3)
Element at position 3: 3
java.lang.IndexOutOfBoundsException: index (4) must not be greater than size (3)
java.lang.NullPointerException: a1 is null!
java.lang.IllegalStateException: Service is not running!

Download the source code

This was an example about Google Guava Preconditions.

You can download the source code here: guavaPreconditionsExamples.zip
Share.

Comments are closed.