I want to add field validations in a method in my application (e.g. field is not null and positive).
private void assertionTest(Integer i) {
// want to first assert here that i is not null and positive
// something like:
// Preconditions.checkArgument( i != null && i > 0, "i should be non null positive number!" );
//
System.out.println( "i: " + i);
}
Java 8 introduces Objects class which has some basic utility methods for null check validation:
public static <T> T requireNonNull(T obj)
public static <T> T requireNonNull(T obj, String message)
But it still lacks exhaustive list of validations which guava's Preconditions class provides, like the below:
checkArgument(boolean) throws IllegalArgumentException
checkState(boolean) throws IllegalStateException
etc.
Is there any some better alternative in Java 8+ for field validation so that I don't have to include external libraries like guava for that?
The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.
Java 8+ (till 12) doesn't have such an approach (maybe in the future some changes will appear).
From pure Java side, you can use assert:
assert <condition> : <message>
In case of assertion fails AssertionError
is thrown with <message>
.
However, you should be sure that is activated by adding -ea
attribute to JVM.
Asserts add more meaningful information to failed cases.
However, the aim of asserts isn't for checking method parameters. Thus, have a look at the second approach.
As an alternative, you can use apache-commons-lang
Validate class:
Validate.notNull(i, "this parameter can't be null")
Validate.isTrue(i > 0, "The value must be greater than zero: %d", i);
This approach is much more preferable for validating parameters for the method.
If you are using Spring framework you could use Assert class.
Snipept From documentattion - Assertion utility class that assists in validating arguments.
Usage looks like:
Assert.notNull(clazz, "The class must not be null");
Assert.isTrue(i > 0, "The value must be greater than zero");
I guess you can use Apache Commons Lang for this. They have a lot of validation methods in Validate class. I'm not sure if it's expressive enough, but if you need anything else it's OK to just write it for yourself, there shouldn't be much code for simple checks.
Additionally, if you ever want to integrate these checks into your main business logic code (not just unit tests), you should take a look at Bean Validation. This way you are definitely not reinventing a wheel and your tests will only have to expect exception from validation framework.
Cheers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With