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
Option 2 is just a glorified container for a stand-alone procedure to add “entry” to the list. Both list and entry details are provided external to the procedure and only “implementation detail” there is lives inside the addEntry method that itself could easily be moved to another class without any code inside the method breaking.
– Roland Tepp Mar 11 '21 at 19:27