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.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

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


+ 9 = eleven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books