naming methods depending on the mutability of the return value?

Hi all,

This is what I usually do in my packages:

public class Application {

protected int x;
protected String y;
protected LinkedHashMap z;

public int getX() { return x; // immutable }
public String getY() { return y; // immutable }
public LinkedHashMap getZReference() { return z; // mutable }
public LinkedHashMap getZ() { return z.clone(); // or similar: mutable, but a safe copy }


By doing so, the final user knows whether the returned object is somewhat “dangerous” or a safe copy.

Is it a good habit in your opinion? Or is it better to always call methods like “getXXX” even if they return mutable objects, and then leave the task of cloning the returned value to the final user?

Thanks for your suggestions,


I would never trust the final user, even if that person is me, heh heh.

Of course it’s all up to you in your own code, but what I generally see is that a library doesn’t have two options for getting the same list. Instead, the accessor method is always called getZ() and the JavaDocs explain whether the returned value is a live view of the original data or not. Don’t forget that documentation is code too!

As an example from Java EE, see the
method. It documents that it returns a copy, and so if you want to modify the original you’d need to call the setter with your version of the list. On the other hand,
documents that changes in the returned set cause changes in the original info.

I know that second one isn’t a getXYZ-named method, but it’s the 1st thing I could think of. :slight_smile:


Hi Bobby, thanks for your answer: I actually ended up implementing “one option only” for every method (and I’m going to javadoc a little to explain what they do…).

Thanks, Marco