java:S6207 - Record constructors with custom implementations are reported as redundant

My Environment

  • Operating system: Microsoft Windows 11 (24H2)
  • SonarLint plugin version: 10.11.1.79663
  • IntelliJ version: IntelliJ IDEA 2024.2.3 (Community Edition)
  • Programming language you’re coding in: Java
  • Is connected mode used: No

Problem / Question:

public record Point(Long x, Long y) {
    public Point(Long x, Long y) {
        if (x == null) throw new IllegalArgumentException("Parameter x cannot be null");
        if (y == null) throw new IllegalArgumentException("Parameter y cannot be null");
        this.x = x;
        this.y = y;
    }
}

SonarLint reports that this constructor is redundant, which seems like a defect?

Hi,

Welcome to the community and thanks for this report!

What rule is it that’s raising an issue here?

 
Thx,
Ann

Thanks for your reply.

The relevant rule is java:S6207: Redundant constructors/methods should be avoided in records.

You can also create a sample code class to observe more information about the java:S6207 rule.

1 Like

Hi,

Thanks for the rule id. I’ve flagged this for the language experts.

 
Ann

EDITED: Removed the assignment from the compact constructor

Hey @ximinghui,
This is a case where the rule seems to be correct to me but the message may be misleading.
Because the component list you are passing is identical to your constructor parameter list (Long x, Long y), your code would gain in simplicity by replacing the custom constructor with a compact constructor.

public record Point(Long x, Long y) {
    public Point {
        if (x == null) throw new IllegalArgumentException("Parameter x cannot be null");
        if (y == null) throw new IllegalArgumentException("Parameter y cannot be null");
    }
}

If you agree, do you think that a clearer issue message would have helped you to get to that solution?

Cheers,

Dorian

2 Likes

Reply to Dorian Burihabwa:

Oh, I see. Haha. Thank you for your explanation, this is a perfect solution. The rule is correct, and perhaps it would be better if it had a more specific reason or provided an action to fix the code.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.