Should you assert not null with the assert statement in production code?

Viewed 12915

I've seen this question but have a few more questions about the usage of the assert keyword. I was debating with a few other coders about using assert. For this use case, there was a method that can return null if certain prerequisites are met. The code I wrote calls the method, then asserts it doesn't return null, and continues to use the returned object.

Example:

class CustomObject {
    private Object object;

    @Nullable
    public Object getObject() {
        return (object == null) ? generateObject() : object;
    }
}

Now imagine I use it like this:

public void useObject(CustomObject customObject) {
    object = customObject.getObject();
    assert object != null;
    // Do stuff using object, which would throw a NPE if object is null.
}

I was told I should remove the assert, that they should never be used in production code, only be used in testing. Is that true?

6 Answers

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 nulls 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.

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.

Surely what you are told is a blatant lie. Here's why.

Assertions are disabled by default if you just execute standalone jvm. When they are disabled, they have zero footprint, hence they will not affect your production application. However, they are probably your best friends when developing and testing your code, and most of testing framework runners enable assertions (JUnit does), so your assertion code is executed when you run your unit tests, helping you detect any potential bugs earlier (e.g. you can add asserts for some business logic boundary checks, and that will help detect some code which uses inappropriate values).

That said, as the other answer suggests, for exactly that reason (they are not always enabled) you cannot rely on assertions to do some vital checks, or (especially!) maintain any state.

For an interesting example of how you could use asserts, have a look here - at the end of the file there's a method singleThreadedAccess() which is called from the assert statement on line 201 and is there to catch any potential multithreaded access in tests.

The other answers already cover this well enough, but there are other options.

For example, Spring has a static method:

org.springframework.util.Assert.notNull(obj)

There are other libraries with their own Assert.something() methods as well. It's also pretty simple to write your own.

However, keep in mind what exceptions you throw if this is a web service. The previous method mentioned, for example, throws an IllegalArgumentException which by default in Spring returns a 500.

In the case of a web service, this is often not an internal server error, and should not be a 500, but rather a 400, which is a bad request.

Use asserts liberally whenever doing so helps catching programming mistakes i.e. bugs.

Do not use assert to catch something that might logically happen i.e. badly formatted input. Use assert only when the error is unrecoverable.

Do not put any production logic in the code that runs when the assertion is checked. If your software is well written this is trivially true but if it's not then you might have subtle side effects and different overall behavior with assertions enabled and disabled.

If your company has "testing code" and "production code" doing the same thing but as different code bases (or different stages of editing), get out of there and never come back. Trying to fix that level of incompetence is probably a waste of your time. If your company doesn't put any assert statement outside of the code of the tests, kindly tell them that asserts are disabled in the production build and that if they aren't, fixing that mistake is now your first priority.

The value of asserts is precisely to be used inside the business logic and not only the test suite. This makes it easy to churn out many high level tests that don't have to explicitly test many things to go through big chunks of your code and trigger all these assertions. In a few of my projects typical tests didn't even really assert anything, they just ordered a calculation to happen based on specific input and this caused hundreds of assertions to be checked and problems to be found even in tiny pieces of logic deep down.

You can use assert any time. The debate come is when to use. For example in the guide :

  • Do not use assertions for argument checking in public methods.
  • Do not use assertions to do any work that your application requires for correct operation.
Related