Should you assert not null with the assert statement in production code?
The most important thing to remember about assertions is that they can be disabled, so never assume they'll be executed.
For backward compatibility, the JVM disables assertion validation by default. They must be explicitly enabled using either the -enableassertions command line argument, or its shorthand -ea:
java -ea com.whatever.assertion.Assertion
So, it's not a good practice to rely on them.
As assertions aren't enabled by default you can never assume they will be executed when used in the code. So you should always check for null values and empty Optionals, avoid using assertions to check inputs into a public method and instead use an unchecked exception... In general do all the checks as if the assertion wasn't there.
Use Objects.requireNonNull(Object)
for that.
Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, [...]
In your case that would be:
public void useObject(CustomObject customObject) {
object = customObject.getObject();
Objects.requireNonNull(object); // throws NPE if object is null
// do stuff with object
}
This function is made for what you want to do: explicitly mark what is not to be null
. The benefit is that you find null
-values right where they should not occur. You will have less troubles debugging problems caused by null
s that are passed somewhere where they shouldn't be.
Another benefit is the flexibility when using this function in contrast to assert
. While assert
is a keyword for checking a boolean value, Objects.requireNonNull(Object)
is a function and can be embedded in code much easier.
Foo foo = Objects.requireNonNull(service.fetchFoo());
// you cannot write it in one line.
Bar bar = service.fetchBar();
assert bar != null;
service.foo(Objects.requireNonNull(service.getBar()));
// you cannot write it in one line.
Bar bar = service.getBar();
assert bar != null;
service.foo(bar);
Keep in mind that Objects.requireNonNull(Object)
is only for null
-checking while assert
is for general assertions. So assert
has different purposes: primarily testing. It has to be enabled, so you can enable it for testing and disable it in production. Use it to seperate testing-only-tests from tests, or rather checks, that are meant for production-code too.