最近使用,sonar代码审查,报错,“ Method parameters, caught exceptions and foreach variables should not be reassigned”
官方提供的例子如下:
1. Noncompliant Code Example:不规范代码示例
`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
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
}
}`
2. Compliant Solution:规范代码示例
`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);
}
}`
我觉得官方给的示例,后面规范的代码并没有高明很多? 请大神解惑。
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…