Sunday, January 4, 2015

Google Gauva API in a one glance: Preconditions and Constraints

allows to check correctness of parameters passed to our method and throw an appropriate exception when necessary.
public final class Preconditions
extends Object
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);
Deprecated. 
Use Preconditions for basic checks. In place of constrained collections, we encourage you to check your preconditions explicitly instead of leaving that work to the collection implementation. For the specific case of rejecting null, consider the immutable collections. This class is scheduled for removal in Guava 16.0.
@Beta
@Deprecated
@GwtCompatible
public final class Constraints
extends Object
Factories and utilities pertaining to the Constraint interface.

let's see how precondition and Constraints works
/**
*
*/
package com.rajkrrsingh.test.guava;

import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.Constraint;
import com.google.common.collect.Constraints;

/**
* @author rks
* @04-Jan-2015
*/
public class GuavaPreCoditionsDemo {

public static void main(String[] args) {
constrainDemo();
preConditionDemo("rks");
}

// create a constrain on the list which will check when you try to add an element on the list, throw exception in constrained voilation
public static void constrainDemo(){
List<Employee> list = Constraints.constrainedList(Employee.getEmployeeList(), new Constraint<Employee>() {

@Override
public Employee checkElement(Employee emp) {
Preconditions.checkArgument(emp.getAge()>30);
return emp;
}
});
System.out.println(list.size());
// allow to add the element in the list
list.add(new Employee("109", "empName", 10210, 38));
System.out.println(list.size());
}

// validate argument passed to the method and throw required exceptions
public static void preConditionDemo(String arg){
System.out.println(Preconditions.checkNotNull(arg).toUpperCase());
}
}



No comments: