About returning a reference in a Java Getter

Introduction

I was writing Java code and thought that the argument was passed by value of the reference, but the return value of the method was returning the reference, so I wrote it for the first post as well.

Getter for an object

If you've written Java, you've probably heard stories about making getters and setters without using public fields as much as possible. Regarding this, this time I would like to consider a Getter that returns an object such as a list. First from the code below

TestList.java


public class TestList {
	private List<String> lst;
	
	public TestList(){
		this.lst = new ArrayList<String>();
	}
	public List<String> getList(){
		return lst;
	}
	public void setList(List<String> lst){
		this.lst = lst;
	}
}

Well, it's a class that wraps List. Next, make the main.

Main.java


public class Main {

	public static void main(String[] args) {
		TestList test = new TestList();
		List<String> l = test.getList();
		l.add("a");
		l.add("b");
		for (String s: test.getList()){
			System.out.println(s);
		}
	}
}

When you do this, you get:

a
b

This is rewriting the private list in the class from the outside (Main) </ b>. In other words, the person who created the TestList class can make unintended changes </ b>. Isn't this dangerous when developing a large number of people?

solution

If you do not want to change it from the outside, you can change getList so that ArrayList is new and then returned as follows.

TestList.java


public class TestList {
	private List<String> lst;
	
	public TestList(){
		this.lst = new ArrayList<String>();
	}
	public List<String> getList(){
		return new ArrayList<String>(lst);
	}
	public void setList(List<String> lst){
		this.lst = lst;
	}
}

Conclusion

When I create a Getter myself, I can't come to a conclusion as to whether it should be written as above or as below. However, from the perspective of encapsulation, I think the code below is more concealing. Please let us know what you think.

Recommended Posts