Guava Preconditions example

Preconditions meaning is to check and validate method input parameters. Let’s see how’s it can be done using Guava’s Preconditions class.

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        checkNotNull(name, "name cannot be null");
        checkArgument(age > 0, "age should be positive number");
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        checkNotNull(name, "name cannot be null");
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        checkArgument(age > 0, "age should be positive number");
        this.age = age;
    }

}
public class PreconditionsExample {
    public static void main(String[] args) {
        Person person = new Person("Greg", -2);
    }
}

[addToAppearHere]

Output

Exception in thread "main" java.lang.IllegalArgumentException: age should be positive number
	at com.google.common.base.Preconditions.checkArgument(Preconditions.java:122)
	at com.blog.Person.(Person.java:15)
	at com.blog.PreconditionsCheck.main(PreconditionsCheck.java:8)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Under the hood Preconditions just checks the expression and throws appropriate exception.