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
modifyList
would be expected to modify the list. – Banksadd
on aList
: it's an optional method, so there is no guarantee it will succeed without an exception (and there is no way of knowing this, either). – Fingered@throws UnsupportedOperationException - if list does not support the add operation
:-) – Foxtailadd
must throw an UOE if it is not a supported operation. – FoxtailList
supportsadd
without callingadd
. All you can do is catch the exception, and hope that you've got failure atomicity. – FingeredmodifyList
method. It's then the caller's responsibility to deal with the problem. – Foxtail