I want to do null checks for my method arguments, like parameters should not be null. Is it okay to use something like this assertNotNull("Map should not be null", filePaths);
in my Java code?
I'm trying to avoid
if(filePaths == null){
throw new IllegalArgumentException("Maps cannot be null");
}
just to keep my code clean from all those null checks. I know I can write a Validator
class of my own and have overloaded notNull
methods but is there something existing and simple to use to not re-invent the wheel.
The only drawback I see of using JUnit
Assert
is that it throws AssertionError
and not IllegalArgumentException
and so forth.
Java Assertion Best PracticesYou should not use assertions to check for valid parameters. Instead, use exceptions. You should assert for null values whenever you can. It is not a good practice to connect the method call directly with the assert method.
exceptions in Java. Developers use assertions to document logically impossible situations and detect errors in their programming logic. At runtime, an enabled assertion alerts a developer to a logic error. The developer refactors the source code to fix the logic error and then recompiles this code.
Don't use asserts for normal error handling Very similar to try and catch , asserts littered all over the code distract the programmer that is reading the code from the business logic. Validating user input — A good program always validates user input, but this should never be done with assertions.
Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type.
If you use Java 7+, you can use:
Objects.requireNonNull(filePaths, "Map should not be null");
Also with a null argument, I would expect a NullPointerException or an IllegalArgumentException, but not an AssertionError.
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