All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S6207.html Maven / Gradle / Ivy

There is a newer version: 8.9.0.37768
Show newest version

Why is this an issue?

In Java 16 records represent a brief notation for immutable data structures. Records have autogenerated implementations for constructors with all parameters, getters, equals, hashcode and toString. Although these methods can still be overridden inside records, there is no use to do so if no special logic is required.

This rule reports an issue on empty compact constructors, trivial canonical constructors and simple getter methods with no additional logic.

Noncompliant code example

record Person(String name, int age) {
  Person(String name, int age) { // Noncompliant, already autogenerated
    this.name = name;
    this.age = age;
  }
}

record Person(String name, int age) {
  Person { // Noncompliant, no need for empty compact constructor
  }
  public String name() { // Noncompliant, already autogenerated
    return name;
  }
}

Compliant solution

record Person(String name, int age) { } // Compliant

record Person(String name, int age) {
  Person(String name, int age) { // Compliant
    this.name = name.toLowerCase(Locale.ROOT);
    this.age = age;
  }
}

record Person(String name, int age) {
  Person { // Compliant
    if (age < 0) {
      throw new IllegalArgumentException("Negative age");
    }
  }
  public String name() { // Compliant
    return name.toUpperCase(Locale.ROOT);
  }
}

Resources





© 2015 - 2025 Weber Informatics LLC | Privacy Policy