摘抄自sonar 的提示,涨了见识了这里使用clone来保持了原对象数据的不可变性,这在一种业务场景是很符合的。但是如果业务上使我就想改变数组或者集合的值呢,而且多数情况下都是想改变的,要是不想让他改变, 那做的赋值操作改变它的值的意义是什么?还是说在多线程的情况会有其他的问题?所以这种方式只是针对某种情况的特例。
Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Mutable class members should never be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.
Instead use an unmodifiable Collection (via Collections.unmodifiableCollection, Collections.unmodifiableList, ...) or make a copy of the mutable object, and store or return the copy instead.
This rule checks that arrays, collections and Dates are not stored or returned directly.
Noncompliant Code Example
class A {
private String [] strings;
public A () {
strings = new String[]{"first", "second"};
}
public String [] getStrings() {
return strings; // Noncompliant
}
public void setStrings(String [] strings) {
this.strings = strings; // Noncompliant
}
}
public class B {
private A a = new A(); // At this point a.strings = {"first", "second"};
public void wreakHavoc() {
a.getStrings()[0] = "yellow"; // a.strings = {"yellow", "second"};
}
}
Compliant Solution
class A {
private String [] strings;
public A () {
strings = new String[]{"first", "second"};
}
public String [] getStrings() {
return strings.clone();
}
public void setStrings(String [] strings) {
this.strings = strings.clone();
}
}
public class B {
private A a = new A(); // At this point a.strings = {"first", "second"};
public void wreakHavoc() {
a.getStrings()[0] = "yellow"; // a.strings = {"first", "second"};
}
}
网友评论