Let's say we have a class with a simple collection (a list for instance). The class contains a constructor, getters and setters. I've been told that it is a bad practice to set the collection directly.
class Example{
private String id;
private List<String> names;
public Example(String id, List<String> names){
this.id = id;
this.names = names;
}
public String getId(){
return id;
}
public List<String> getNames(){
return names;
}
public void setId(String id){
this.id = id;
}
public void setNames(List<String> names){
this.names = names;
}
}
Can anyone point the disadvantages of writing the method setNames()?
The logic behind set and get operations is to allow validation or replacing of inner representation, if you let an external class set the specific implementation, you lose control over the insertion logic (allows duplicates? is ordered?, is mutable?), and you make you object harder to use, as the users of it have to decide that, when is very probable that they don't care.
A lot of the built-in collections are mutable, so storing such a value may allow an external class to modify the internal state of your Example in a way you did not plan. Consider the following snippet:
List<Stirng> names = new ArrayList<>();
names.add("Stack");
names.add("Overflow");
Example example = new Example();
example.setNames(names);
// example.getNames() returns ["Stack", "Overflow"]
names.add("Exchange");
// example.getNames now returns ["Stack", "Overflow", "Exchange"]!
A safer approach could be to copy the contents of the passed list:
public void setNames(List<String> names){
this.names = new ArrayList<>(names);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With