Question

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?

  1. 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");
    }
}
  1. 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

Was it helpful?

Solution

One of the principles of object-oriented programming is encapsulation. It says that one should hide the internal structure of the object and prevent direct access to it.

In your case this means that those who use your class should not "know" whether your class Dictionary uses ArrayList or Map or something other to store elements.

That's why option 1 is better.

One of benefits of such approach is that you can change the implementation of the class Dictionary whenever you wish, e.g. you may decide to use a tree structure instead of list, and all who use your class will not need to modify their code.

OTHER TIPS

Option 1, without question.

The whole point of your Dictionary class is to encapsulate the list and any other information you need to make your dictionary work. You already have access to the class's fields, so passing them as parameters is pointless.

Your Option 2 exposes the internal details of your class, defeating its purpose.

In real life, very often you don’t just add an entry to a list, but it has consequences. Like an application could be displaying the entries of a list, and adding something needs to trigger a whole sequence of events. If you tell the object to add an item, it can take care of everything. If you insert an item yourself into the list, that can have negative side effects. And if not know, then next year.

Licensed under: CC-BY-SA with attribution
scroll top