Let’s say I have a class A that has a list of related elements (type of elements not relevant):
public class A {
private List<String> list;
public List<String> getList() {
return list;
}
public void addElement(String element) {
list.add(element);
}
}
Now I want access to this list from another class, Client. I need to add a new element. The question, a more phylosophical one, is how best is this done from a design point of view.
public class Client {
private A a = new A();
public void method1() {
a.getList().add("");
}
public void method2() {
a.addElement("");
}
}
If anyone could point out any advantage of any of these methods, would be much appreciated.
Thanks.
Generally your
getList()method is considered bad style. If classAreturns a reference to its actualList, than a caller might callclear()on that list, or add a million elements to it, or so who-knows-what-all. It’s a much better idea to return only anIterator, or only a read-only view of theListusingCollections.unmodifiableList().This means your solution 2,
addElement()is better; theaddElement()method might contain code to validate the added elements, limit the size of the list, or whatever. Andclear()would not be accessible.