I would like to know what is a more appropriate way to code in Java. Is it generally better to pass entire objects in the method's parameters or just using the fields from the class?
- Using the field:
public class Dictionary {
ArrayList<Definition> list;
public Dictionary() {
this.list = new ArrayList<Definition>();
}
public void newEntry(String key, String value) {
this.list.add(new Definition(key, value));
}
}
public class SampleTests {
@Test
public void Tests()
{
Dictionary d = new Dictionary();
d.newEntry("Apple", "A fruit");
}
}
- Passing an object:
public class Dictionary {
public Dictionary() {
//this.list = new ArrayList<Definition>();
}
public void newEntry(String key, String value, ArrayList<Definition> list) {
list.add(new Definition(key, value)); //I'm not using field from this class!
}
}
public class SampleTests {
@Test
public void Tests()
{
Dictionary d = new Dictionary();
ArrayList<Definition> list = new ArrayList<>();
d.newEntry("Apple", "A fruit", list);
}
}
I've checked this related question, but the guys' answers do not help me much