Tuesday, September 18, 2012

Google Guava and Preconditions

In my previous article I talked about "single line else", now I'll share with you how to avoid the tedious code writing of input control blocks.

Google Guava library allows you to avoid the writing of classic if throw.
For example, code like this:
    public static int division(int a, int b) {
        if(b == 0)
            throw new IllegalArgumentException("Cannot divide by zero.")
        return a / b;
    }

With Guava becomes:
    public static int division(int a, int b) {
        Preconditions.checkArgument(b != 0, "Cannot divide by zero.")
        return a / b;
    }
Pay attention to the condition b != 0, the library allows you to formerly define a precondition so the variable b will be checked for the expected values instead of the exceptional ones.
Guava Preconditions utility methods are a lot, one for each type of exception, so you can write a big variety of if then throw, here's the list:


Related posts:

No comments:

Post a Comment