Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

为什么 ,方法参数/捕获的异常/foreach的变量不应该被重新赋值?

最近使用,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);

}

}`

我觉得官方给的示例,后面规范的代码并没有高明很多? 请大神解惑。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

第一个,this.name 指的是你上面定义的,类里面的一个属性,name指的是构造函数的入参,把入参赋给类的属性,要用 this.name = name

第二个,单纯的想返回两个入参的和的话,直接 return a + b就行了,没必要设个中间变量。而且就算设中间变量了也应该新建一个 int temp = 0;,不要对入参做修改。

第三个看起来跟形参和实参的关系。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...