Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it bad practice to allow to set a collection?

Tags:

java

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()?

like image 627
Yuval Avatar asked Oct 26 '25 07:10

Yuval


2 Answers

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.

like image 170
leoconco Avatar answered Oct 27 '25 21:10

leoconco


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);
}
like image 29
Mureinik Avatar answered Oct 27 '25 22:10

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!