Do you know Java: Parameter validation
Checking method parameters is crutial to avoid inconvenient situations with null pointers or undesired values. Assertion and exception handling are two ways to give feedback to users about parameters.
What if we are intended to validate the parameters of a function? What if we liked to set up preconditions? How can we avoid working with null objects?
In this post we take a look at two approaches. At first, we see how we can check parameters with assertion and what its pros and cons are. Then we see how to use exception handling for the same purpose.
Assertion
Java provides an assert
keyword to use it against logical expressions as shown below.
The drawback of this approach is that assertion mechanism can be switched off
in runtime. What’s more, switched off is the default state of asserts.
public void print(Person person) {
assert null == person : NULL_CHECK_MSG;
// ...
}
So, once we want to use it, we have to execute java
command with
-enableassertions
or -ea
:
java -ea Main
If condition fails then AssertionError
is raised.
IllegalArgumentException
While assertions is switchable, we can disable that in runtime, exception handling is completely part of the code with language level features (inheritance, ctor, overloading, parameter passing).
public void print(Person person) {
if (null == person) {
throw new IllegalArgumentException(NULL_CHECK_MSG);
}
// ...
}
Objects.requireNonNull
The best way to validate parameters against null
is to use a solutions from
the standard edition or a framework.
Here is a solution among many of them.
public void print(Person person) {
Objects.requireNonNull(person, "person cannot be null");
// ...
}
While assertion is switched off by default in runtime, exception is still part
of the language. While assertion is an error, IllegalArgumentException
is
an exception. Never handle errors.
As we see, favour exception over assertion.
Code can be found: https://github.com/torokmark/do-you-know-java