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);
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.
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;


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

public static void main(String[] args) {

// 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>() {

public Employee checkElement(Employee emp) {
return emp;
// allow to add the element in the list
list.add(new Employee("109", "empName", 10210, 38));

// validate argument passed to the method and throw required exceptions
public static void preConditionDemo(String arg){

Post a Comment