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.
 

Reference: Guava Preconditions Class from our JCG partner Dustin Marx at the Inspired by Actual Events blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Guava Preconditions Class"

  1. Yuri NotForPublc says:

    overcoded examples, short article, and there was already published the better article about Guava Preconditions…

Leave a Reply


eight − = 0



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close