Guava Preconditions Tutorial

In this article, we will examine how and why to use Guava Preconditions. Guava Preconditions provide a number of static methods to verify a constructor or a method in Java is invoked with the proper arguments or parameters. Preconditions standardize the way an application handles such errors and eliminates the mundane task of repeatedly implementing similar blocks of code.


Preconditions help guarantee the successful execution of code by ensuring expectations are satisfied. If provided conditions are different than the expections, immediate feedback is provided about the issue.

Preconditions replace the need for boilerplate code such as the block shown below:


public void setSomeParam(Object param)
{
   if (param == null)
   {
      throw new IllegalArgumentException("Param cannot be null");
   }
}

By using Preconditions, it is possible to achieve the same check in a more concise manner:


public void setSomeParam(Object param)
{
   // Assuming static import of Preconditions.checkArgument;
   checkArgument(param == null, "Param cannot be null");
}

 

Guava Preconditions Example


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

public class PreconditionsExample
{
   private int myNumber;

   private String myString;

   private Object myObject;

   private int[] myArray;

   public PreconditionsExample(int number, String string, int[] array)
   {
      checkArgument(number > 0, "Number must be greater than 0");
      notNull(string);

      myNumber = number;
      myString = string; 
      myArray = array;
   }

   public void init(Object object)
   {
      myObject = object;
   }

   public Object getObject()
   {
      checkState(object != null, "Object is null");
      return myObject;
   }
}


Here is a summary of the methods in the Preconditions class. Each method comes in two varieties, one taking an error message, one without.

  • checkNotNull() – throws NullPointerException if argument is null.
  • checkArgument() – throws IllegalArgumentException if expression evaluates to false.
  • checkState() – throws IllegalStateException if expression evaluates to false.
  • checkElementIndex() throws IndexOutOfBoundsException if index is out of bounds for the provided collection.