0

You have an object that contains a list:

public class MyPojo {
    private List<Object> list;
}

And you want to add an item to this pojo's list.
What's better ?

1) You add a getter, get the list and add an object to it

public class MyPojo {
    private List<Object> list;
    public List<Object> getList() {
        return list;
    }
}
// and then use
new MyPojo().getList().add(Object);

2) You write a addItem() in your Pojo that insert the object to the list

public class MyPojo {
    private List<Object> list;
    public void addItem(Object item) {
        list.add(item);
    }
}
// and then use
new MyPojo().addItem(Object);

What is the best pratice for code quality in this case ? Thanks !

lmo
  • 497
  • 5
  • 23

3 Answers3

1

If you've the freedom to choose, always prefer the second way, i.e., calling the method which internally modifies the instance field.

In the first one, you're clearly exposing the List<Object> instance field, which is a very poor way of coding. You should never adopt that.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
1

All answers will be opinionated. I think that #1 breaks encapsulation, so I'd go for #2. However, I would do this only for domain objects, i.e. I wouldn't do it for data transfer objects (DTO's) or any other datavalue.

fps
  • 33,623
  • 8
  • 55
  • 110
0

Say you chose the first method, which modifies the internal representation of the class without its knowledge. A lot of client code is written that modifies the list.

Later, you change the class in such a way that you need to know if the list has been modified. Or maybe you want to change the internal representation. But now there's all this external code that violates encapsulation. It's going to be either more expensive or infeasible to modify the external code, depending on whether or not you can modify it.

The second method encapsulates the data. You leave the door open to changing the internal representation, or monitoring changes.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151