DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Application Architecture Design Principles
  • How To Scan and Validate Image Uploads in Java
  • Security Challenges for Microservice Applications in Multi-Cloud Environments
  • A Data-Driven Approach to Application Modernization

Trending

  • Application Architecture Design Principles
  • How To Scan and Validate Image Uploads in Java
  • Security Challenges for Microservice Applications in Multi-Cloud Environments
  • A Data-Driven Approach to Application Modernization
  1. DZone
  2. Coding
  3. Java
  4. Guava Preconditions Class

Guava Preconditions Class

Dustin Marx user avatar by
Dustin Marx
·
Dec. 31, 11 · Interview
Like (0)
Save
Tweet
Share
6.30K Views

Join the DZone community and get the full member experience.

Join For Free

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.

 

From http://marxsoftware.blogspot.com/2011/10/guava-preconditions-class.html

Precondition Google Guava

Opinions expressed by DZone contributors are their own.

Trending

  • Application Architecture Design Principles
  • How To Scan and Validate Image Uploads in Java
  • Security Challenges for Microservice Applications in Multi-Cloud Environments
  • A Data-Driven Approach to Application Modernization

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: