Friday, June 4, 2010

Using Preconditions from Google Guava library

Google Guava library provides the nice way to validate and check method parameters - Preconditions.

Usually we stuck with such kind of validation in the beginning of every public method:
public static void writeAllText( File file, String contents )
 throws FileNotFoundException, IOException {
 
 if( file == null ) {
  throw new IllegalArgumentException( "File should not be null" );
 }
 if( !file.exists() ) {
  throw new FileNotFoundException( "File does not exist: " + file );
 }
 if( !file.isFile() ) {
  throw new IllegalArgumentException( "Should not be a directory: " + file );
 }
 if (!file.canWrite()) {
  throw new IllegalArgumentException( "File cannot be written: " + file );
 }

 Writer output = new BufferedWriter( new FileWriter( file ) );
 try {
  output.write( contents );
 }
 finally {
  output.close();
 }
}
Using Guava Preconditions we can replace all these regular If-Then statements to helper methods:
public static void writeAllText( File file, String contents )
 throws FileNotFoundException, IOException {

 // parameters validation using Preconditions
 Preconditions.checkNotNull( file );
 Preconditions.checkArgument( !file.exists(), "File does not exist: %s", file );
 Preconditions.checkArgument( !file.isFile(), "Should not be a directory: %s", file );
 Preconditions.checkArgument( !file.canWrite(), "File cannot be written: %s", file );

 Writer output = new BufferedWriter( new FileWriter( file ) );
 try {
  output.write( contents );
 }
 finally {
  output.close();
 }
}
There are five static methods you can use for that purpose:
  1. Preconditions.checkNotNull()
  2. Preconditions.checkArgument()
  3. Preconditions.checkElementIndex()
  4. Preconditions.checkPositionIndex()
  5. Preconditions.checkState()
Please note that %s placeholder in the error message templates is the only available because they don't correspond to the String.format() specifiers.

3 comments:

  1. The boolean argument to Preconditions.checkArgument() should be true or the exception will be thrown. In other words, it should be Preconditions.checkArgument(file.exists(), ...). You're checking that the file does exist.

    ReplyDelete
  2. Colin is right - check the javadoc:
    "Simple static methods to be called at the start of your own methods to verify correct arguments and state. This allows constructs such as

    if (count <= 0) {
    throw new IllegalArgumentException("must be positive: " + count);
    }

    to be replaced with the more compact

    checkArgument(count > 0, "must be positive: %s", count);"

    Think as if using asserts in Java

    ReplyDelete
  3. The syntax is much nicer when you use the static import.

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

    ReplyDelete