Templates by BIGtheme NET

Cleaner Code with Guava’s Preconditions

Description :
There are more simpler and cleaner ways to avoid asserts and handling null checks.
Guava’s Preconditions are used for checking method arguments, states, etc.

When a condition is false the Precondition will throw the expected exception.
The class Preconditions may throw IllegalArgumentException, NullPointerException,
IllegalStateException and IndexOutOfBoundsException.

Here are some examples that I took that can be shortened to single line of code.

1) Illegal Argument Exception :
Example :

final XmlRdtMessageWrapper message = inStateContext.getRequestAttribute(StateRequestAttributeKey.MESSAGE);
if (message == null) {
    throw new IllegalArgumentException("State context does not have a valid MESSAGE attribute");

This can be handled in two ways, throwing null pointer exception or throwing illegal argument
exception like the developer decided in the above.

If we want to throw illegal argument exception we can do it this way

Preconditions.checkArgument(message!=null,"StateContext does not have a valid MESSAGE attribute");

2) Java Asserts for null checks, well asserts are not used in production and should be noted that
they throw Error not Exception when used in try catches.
Example :

try {
final Che che = cheHandler.getCheByNaturalKey(inCheNaturalKey);
assert che != null;
} catch (final Exception e) {
// doesn’t catch AssertionError

Best way to avoid this is to use Guava’s Preconditions checkNotNull method which throws NullPointerException

Preconditions.checkNotNull(che, "Che must not be null");

*** Venkat – Happy leaning ****