Tuesday, October 25, 2011

Guava Preconditions Class

Anyone who's written much Java has probably written methods that begin with conditionals that verify either the provided parameters or the state of the object being acted upon before proceeding with the remainder of the method's implementation. These can add verbosity to the method and sometimes, especially if there are multiple checks, can almost drown out the interesting business logic of the method. One way to reduce this clutter is to use Java assertions, but these are disabled at runtime by default. In fact, it is advised to "not use assertions for argument checking in public methods" for this reason and to use appropriate runtime exceptions instead. Guava provides a handy Preconditions class with aesthetic advantages of assertions, but which uses the normal Java exception mechanism and is not disabled at runtime. This post provides some illustrative examples of Guava's Preconditions class in action.

The next code listing shows contrived examples using Guava's Preconditions class. The example demonstrate use of static methods on the Preconditions class to check a parameter for null, check a parameter's placement in a provided array, check to ensure a valid value has been provided for a parameter, and to check that the state of the object on which the method is invoked is appropriate for that method's execution. Note also that I made use of the static import for the Preconditions class so that I am able to call its static methods without need to scope each call with the class name.

GuavaPreconditionsDemo.java
package dustin.examples;

import static java.lang.System.err;
import static com.google.common.base.Preconditions.*;

/**
 * Simple demonstration of Guava's Preconditions support.
 * 
 * @author Dustin
 */
public class GuavaPreconditionsDemo
{
   private final boolean initialized = false;

   /**
    * Demonstrate Guava's Preconditions.checkNotNull methods.
    * 
    * @param parameter Parameter that is checked for null-ness.
    */
   public void testForNonNullArgument(final String parameter)
   {
      final String localParameter = checkNotNull(parameter, "Provided parameter is unacceptably null.");
   }

   public void testDivisorNotZero(final int divisor)
   {
      checkArgument(divisor != 0, "Zero divisor not allowed.");
   }

   public void testArrayElement(final String[] strArray, final int indexNumber)
   {
      final int index = checkElementIndex(indexNumber, strArray.length, "String array index number");
   }

   public void testArrayPosition(final String[] strArray, final int indexNumber)
   {
      final int index = checkPositionIndex(indexNumber, strArray.length, "String array index number");
   }

   public void testState()
   {
      checkState(this.initialized, "Cannot perform action because not initialized.");
   }

   public static void printHeader(final String newHeaderText)
   {
      err.println("\n==========================================================");
      err.println("== " + newHeaderText);
      err.println("==========================================================");      
   }

   /**
    * Main function for executing demonstrations of Guava's Preconditions.
    */
   public static void main(final String[] arguments)
   {
      final GuavaPreconditionsDemo me = new GuavaPreconditionsDemo();

      printHeader("Preconditions.checkNotNull");
      try
      {
         me.testForNonNullArgument(null);
      }
      catch (NullPointerException npe)
      {
         npe.printStackTrace();
      }

      printHeader("Preconditions.checkArgument");
      try
      {
         me.testDivisorNotZero(0);
      }
      catch (IllegalArgumentException illArgEx)
      {
         illArgEx.printStackTrace();
      }

      printHeader("Preconditions.checkElementIndex");
      try
      {
         me.testArrayElement(new String[]{"Dustin", "Java"}, 3);
      }
      catch (IndexOutOfBoundsException ioobEx)
      {
         ioobEx.printStackTrace();
      }

      printHeader("Preconditions.checkPositionIndex");
      try
      {
         me.testArrayPosition(new String[]{"Dustin", "Java"}, 3);
      }
      catch (IndexOutOfBoundsException ioobEx)
      {
         ioobEx.printStackTrace();
      }

      printHeader("Preconditions.checkState");
      try
      {
         me.testState();
      }
      catch (IllegalStateException illStateEx)
      {
         illStateEx.printStackTrace();
      }
   }
}

Each of the cases demonstrated in the code listing above checked for preconditions on the method parameters or on the state of the object against which the method was being invoked without use of "noisy" conditional statements. Use of the static import allowed very concise expression of the conditions to be checked, Much of the class is the "main" function, used as a "test driver" in this case. I placed the calls within try-catch block to make sure all demonstrations are executed. The output of running the above is shown next.

Output From Executing Above Class
==========================================================
== Preconditions.checkNotNull
==========================================================
java.lang.NullPointerException: Provided parameter is unacceptably null.
 at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:204)
 at dustin.examples.GuavaPreconditionsDemo.testForNonNullArgument(GuavaPreconditionsDemo.java:22)
 at dustin.examples.GuavaPreconditionsDemo.main(GuavaPreconditionsDemo.java:62)

==========================================================
== Preconditions.checkArgument
==========================================================
java.lang.IllegalArgumentException: Zero divisor not allowed.
 at com.google.common.base.Preconditions.checkArgument(Preconditions.java:88)
 at dustin.examples.GuavaPreconditionsDemo.testDivisorNotZero(GuavaPreconditionsDemo.java:27)
 at dustin.examples.GuavaPreconditionsDemo.main(GuavaPreconditionsDemo.java:72)

==========================================================
== Preconditions.checkElementIndex
==========================================================
java.lang.IndexOutOfBoundsException: String array index number (3) must be less than size (2)
 at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:301)
 at dustin.examples.GuavaPreconditionsDemo.testArrayElement(GuavaPreconditionsDemo.java:32)
 at dustin.examples.GuavaPreconditionsDemo.main(GuavaPreconditionsDemo.java:82)

==========================================================
== Preconditions.checkPositionIndex
==========================================================
java.lang.IndexOutOfBoundsException: String array index number (3) must not be greater than size (2)
 at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:351)
 at dustin.examples.GuavaPreconditionsDemo.testArrayPosition(GuavaPreconditionsDemo.java:37)
 at dustin.examples.GuavaPreconditionsDemo.main(GuavaPreconditionsDemo.java:92)

==========================================================
== Preconditions.checkState
==========================================================
java.lang.IllegalStateException: Cannot perform action because not initialized.
 at com.google.common.base.Preconditions.checkState(Preconditions.java:145)
 at dustin.examples.GuavaPreconditionsDemo.testState(GuavaPreconditionsDemo.java:42)
 at dustin.examples.GuavaPreconditionsDemo.main(GuavaPreconditionsDemo.java:102)

The different static Preconditions methods throw different types of runtime exceptions when a specified condition is violated. They throw exceptions that tend to be appropriate for the particular case that is violated. This means that in most cases the result of a Preconditions static method call is the same as one would likely throw explicitly for that condition, but with much less code to make the check and throw the exception. I did not show it in this post, but overloaded versions of these static methods also allow for string arguments to be provided to fill placeholders in a patterned String. This is helpful for placing values associated with the errant condition in the exception message.

Conclusion

Guava eases the coding and improves the fluency and readability of contract checking in methods. It offers the advantages of assertions' concise syntax coupled with the advantages of traditional throwing of runtime exceptions.