As per the title, are there any smells surrounding the provision of a setter that accepts a List
instantiation for assignment to a instance variable?
i.e.
public class Test{
private List<St开发者_运维技巧ring> strings;
public Test() {}
public void setStrings(List<Strings> strings) {
this.strings = strings;
}
}
What could be a better approach (domain specifics aside)?
The problem with your code is that the caller of your setter can modify the list, because the caller still has a reference. Consider this code:
Test test = new Test();
List<String> list = new ArrayList<String>();
test.setStrings(list);
list.clear(); // oops! the state of Test has changed without Test knowing!
The better approach is to use a copy of the list:
public void setStrings(List<Strings> strings) {
this.strings = new ArrayList<String>(strings);
}
This fine (I assume you have a getter as well) The only thing I might do differently is take a copy of the list rather than a direct assignment.
public void setStrings(List<Strings> strings) {
this.strings = new ArraysList<String>(strings);
}
精彩评论