Java record with a validating constructor

Make sure to read this post before raising a thread here:

Then tell us:

  • What language is this for? Java
  • Which rule? java:S6207
  • Why do you believe it’s a false-positive/false-negative? false positive
  • Are you using
    • SonarQube Cloud?
    • SonarQube Server / Community Build - which version? Data Center Edition v2025.2 (105476)
    • SonarQube for IDE - which IDE/version? IntelliJ 2024.3.7 (Ultimate Edition), SonarQube for IDE 11.7.0.83838
      • in connected mode with SonarQube Server / Community Build or SonarQube Cloud? Yes
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

We’re migrating our codebase from lombok annotations to records where possible. We have a Validateable interface, and all classes extending it implement the void validate() function and call it at the end of the constructor.

public record ExampleParams(String foo) implements Validateable {
  public ExampleParams(String foo) {
    this.foo = foo;
    validate();
  }

  @Override
  private validate() {
    if (this.foo == null || this.foo.length() > 15) {
     throw IllegalArgumentException("Parameter foo must be a string between 0 and 15 characters long");
  }
}

This does not work with the compact constructor, because the properties would not yet be populated when the function is called. One possible non-sonar-flagged solution would be to re-write the validate function to take parameters instead of getting them from this, but that would not work as well with inheritance (we sometimes call super.validate())

Hi @pshem,

Sorry for the late reply. I see that how the validation pattern you describe would conflict with S6207. If this pattern is considered standard in your project/organization, you could consider disabling the rule altogether.

However, based on the short example you shared, I don’t see what prevents you from validating the value of the foo parameter in compact constructor. The call to validate is self-imposed here. Is there another place where validate would be called outside of the constructor?

Still, I will file a ticket to document that a method invocation within a constructor should be considered as non-redundant and should therefore prevent S6207 from raising on the constructor.

Cheers,

Dorian