Java rule to prevent use of assert in production code

Please follow this template to help us specify this new rule:

  • description of the Rule.
    Usage of assert java feature is not recommended, as its a compiler option whether the check is enabled or not.
  • snippet of Noncompliant Code
  private static void foo(byte[] data) {
    assert data.length == 16 : INVALID_DATA_LENGTH_MESSAGE;
    ...
  }
  • snippet of Compilant Code (fixing the above noncompliant code)
  private static void foo(byte[] data) {
    if (data.length != 16) throw new IllegalArgumentException(INVALID_DATA_LENGTH_MESSAGE);
    ...
  }

In general its bad practice to have error handling only on console. Using logging frameworks and/or exception handling is the preferred way.

Hey there.

Does this rule cover the need? Assertions should not be used in production code.

Sadly not:

Note: this does not apply for assert from Java itself

I would argue that using assert for argument validation on public methods is bad practice in general.
assert is intended to fail early whenever (due to a bug) a condition becomes true that the developer is sure “could never happen”.

For example, “I know for certain that this list here has an even number of items; but if it didn’t, the code later on would not work properly and might throw confusing exceptions, because it relies on the fact that the number should be even. By using assert, I can state the precondition as code, and fail early, if a bug gets introduced that breaks the precondition.”

See also this discussion: java - Why should assertions not be used for argument checking in public methods? - Stack Overflow

Hey Michael,

You’re right, S5960 is not about the assert keyword but unit tests. But we also have a rule S4274 - Asserts should not be used to check the parameters of a public method available for Java.

This should cover exactly your case, except not for private methods. The reason is, like @bduderstadt pointed out, assert is meant to check internal states/conditions/constraints for which the developer is sure they hold true unless the developer made a mistake. Since private methods cannot be called by anyone else, parameters of private methods can be considered part of the internal state, and hence, using assert should be allowed.

I think we should extend the rule though so that also protected and package-protected methods are reported because they can be called from outside the class. I created a ticket here.

BR,

Marco

1 Like