javacopymethod-parameters

Is mutating object-parameters in a method(in Java) a bad practice?


I have a question about mutating method-paramaters(which are objects) in a method.

I read and heard multiple times that it is a bad practice to mutate a object in a method which was passed in as a paramater. As example:

public void modifyList(List<Object> list) {
    list.add(new Object());
}

Instead, the passed in Object should be copied, the mutation should be performed on the copied object and the copied object should be returned. As example:

public List<Object> getModifiedList(List<Object> list) {
    List copy = new List<Object();
    //Make a deep copy if it would be necessary
    for(Object o : list) {
        copy.add(o.clone());
    }
    //Modify the copy
    copy.add(new Object());
    //return the copy
    return copy;
}

I understand that the second method has less potential for side effects because it doesn't mutate the input parameter.

But is this really the way to go? The performance would suffer because a lot of deep copys have to be created. Also it would cost a lot of time implement Copy-Constructors and implement clone-methods for all classes. Also it would increase the LOC immense.

In practice I don't see this pattern(copy the method-parameter) often.

Could somebody with a lot of experience(working as a programmer/software developer for years) answer this?

Greetings Maverin


Solution

  • Both methods are fine and could be the correct choice depending on your use case. Just make sure that you name them in a way that makes the intent clear and write some javadoc.

    It's then up to the developer to decide whether having the original list mutated is ok or not, and if not, pass a copy or use a different method.

    For example, this method from the JDK mutates an existing list, but its intent and documentation are very clear.