Sunday 9 August 2015

Guava Preconditions class


Preconditions class provides number of static methods to verify the preconditions of our code.

1.Check for valid arguments
Preconditions class provides checlArgument method, to verify given argument. Preconditions class provides three variants of checkArgument method.

public static void checkArgument(boolean expression)
public static void checkArgument(boolean expression, @Nullable Object errorMessage)
public static void checkArgument(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs)

Above methods return IllegalArgumentException, if the expression evaluates to false.

Following application checks for username.
import com.google.common.base.Preconditions;

public class PreConditionsEx {

  public static void validate(String userName) {
    Preconditions.checkArgument(userName.length() > 7,
        "Given userName %s must has minimum 7 characters", userName);
  }

  public static void main(String args[]) {
    String userName = "abcd";
    validate(userName);
  }
}

When you tries to run above program, you will get following error.

Exception in thread "main" java.lang.IllegalArgumentException: Given userName abcd must has minimum 7 characters
         at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145)
         at guava.PreConditionsEx.validate(PreConditionsEx.java:8)
         at guava.PreConditionsEx.main(PreConditionsEx.java:14)

2. Check index in arrays, strings, lists etc.,
Preconditions class provides following methods to check for valid indexes in arrays, strings, lists etc.,

public static int checkElementIndex(int index, int size)
public static int checkElementIndex(int index, int size, @Nullable String desc)


If index is <=0 (or) >= size, then checkElementIndex method throws IndexOutOfBoundsException.
import com.google.common.base.Preconditions;

public class PreConditionsEx {

  public static int getElementAt(int index, int arr[]) {
    Preconditions.checkElementIndex(index, arr.length,
        "Index must >=0 and <= " + arr.length);
    return arr[index];
  }

  public static void main(String args[]) {
    int a[] = { 2, 3, 5, 7, 1, 3, 4, 6 };
    getElementAt(-3, a);
  }
}

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index must >=0 and <= 8 (-3) must not be negative
         at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:310)
         at guava.PreConditionsEx.getElementAt(PreConditionsEx.java:8)
         at guava.PreConditionsEx.main(PreConditionsEx.java:14)


3. Check for null conditions
Preconditions class provides following methods to check for null conditions.

public static <T> T checkNotNull(T reference)
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage)
public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs)

If ‘reference’ is null, then this method throws NullPointerException.
import com.google.common.base.Preconditions;

public class PreConditionsEx {

  public static void validate(String userName) {
    Preconditions.checkNotNull(userName, "User name must not be null");
    Preconditions.checkArgument(userName.length() > 7,
        "Given userName %s must has minimum 7 characters", userName);
  }

  public static void main(String args[]) {
    String userName = null;
    validate(userName);
  }
}

When you tries to run above program, you will get following error.

Exception in thread "main" java.lang.NullPointerException: User name must not be null
         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:226)
         at guava.PreConditionsEx.validate(PreConditionsEx.java:8)
         at guava.PreConditionsEx.main(PreConditionsEx.java:15)


4. Check for valid sub range of list, array, String etc.,
Preconditions class provides checkPositionIndexes method, to check for valid indexes (start and end).

public static void checkPositionIndexes(int start, int end, int size)

Checks that [start, end) is a valid sub range of a list, string, or array with the specified size. If not in range, it throws IndexOutOfBoundsException.
import com.google.common.base.Preconditions;

public class PreConditionsEx {

  /* Print elements of array from start to end */
  public static void printArr(int arr[], int start, int end) {
    Preconditions.checkPositionIndexes(start, end, arr.length);
    for (int i = start; i < end; i++) {
      System.out.println(arr[i]);
    }
  }

  public static void main(String args[]) {
    int arr[] = { 2, 3, 5, 7, 11, 13, 15, 17 };

    printArr(arr, 3, 10);
  }
}

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: end index (10) must not be greater than size (8)
         at com.google.common.base.Preconditions.checkPositionIndexes(Preconditions.java:383)
         at guava.PreConditionsEx.printArr(PreConditionsEx.java:9)
         at guava.PreConditionsEx.main(PreConditionsEx.java:18)

5. Check Boolean expressions
By using checkState method, you can check for Boolean expressions.

public static void checkState(boolean expression)
public static void checkState(boolean expression, @Nullable Object errorMessage)
public static void checkState(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs)


Above methods throw IllegalStateException, if expression evaluates to false.
import com.google.common.base.Preconditions;

public class PreConditionsEx {

  public static int empIds[] = { 2, 3, 5, 7, 11, 13, 15, 17 };

  public static void printEmpDetail(int empId) {
    Preconditions.checkPositionIndex(empId, empIds.length);
    Preconditions.checkState(checkEmployeeIdFromDB(empId));
    System.out.println("Employee id " + empId + " exist in database");
  }

  public static boolean checkEmployeeIdFromDB(int empId) {
    for (int i = 0; i < empIds.length; i++) {
      if (empId == empIds[i])
        return true;
    }
    return false;
  }

  public static void main(String args[]) {
    printEmpDetail(7);
    printEmpDetail(21);
  }
}

Output
Employee id 7 exist in database
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (21) must not be greater than size (8)
         at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:353)
         at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:336)
         at guava.PreConditionsEx.printEmpDetail(PreConditionsEx.java:10)

         at guava.PreConditionsEx.main(PreConditionsEx.java:25)






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment