Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use Junit Assert API in Java production code

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.

like image 852
Charu Khurana Avatar asked Jul 12 '13 17:07

Charu Khurana


People also ask

Is it good practice to use assert in Java?

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.

When should I use assert in Java?

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.

Is assert good practice?

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.

Why should you not use assertions to check parameters?

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.


1 Answers

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.

like image 157
assylias Avatar answered Sep 20 '22 05:09

assylias