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

org.sonar.l10n.java.rules.squid.S1226.html Maven / Gradle / Ivy

The newest version!

While it is technically correct to assign to parameters from within method bodies, it is better to use temporary variables to store intermediate results.

This rule will typically detect cases where a constructor parameter is assigned to itself instead of a field of the same name, i.e. when this was forgotten.

Allowing parameters to be assigned to also reduces the code readability as developers will not be able to know whether the original parameter or some temporary variable is being accessed without going through the whole method.

Moreover, some developers might also expect assignments of method parameters to be visible from callers, which is not the case and can confuse them.

All parameters should be treated as final.

Noncompliant Code Example

class MyClass {
  public String name;

  public MyClass(String name) {
    name = name;                    // Noncompliant - useless identity assignment
  }

  public int add(int a, int b) {
    a = a + b;                      // Noncompliant

    /* additional logic */

    return a;                       // Seems like the parameter is returned as is, what is the point?
  }

  public static void main(String[] args) {
    MyClass foo = new MyClass();
    int a = 40;
    int b = 2;
    foo.add(a, b);                  // Variable "a" will still hold 40 after this call
  }
}

Compliant Solution

class MyClass {
  public String name;

  public MyClass(String name) {
    this.name = name;               // Compliant
  }

  public int add(int a, int b) {
    return a + b;                   // Compliant
  }

  public static void main(String[] args) {
    MyClass foo = new MyClass();
    int a = 40;
    int b = 2;
    foo.add(a, b);
  }
}

See

  • MISRA C:2012, 17.8 - A function parameter should not be modified




© 2015 - 2025 Weber Informatics LLC | Privacy Policy