So I’ve always been told that it’s bad practice to modify arguments to methods (at least when it’s not intuitive). Normally I’d use something simple, like:
public Type method(Type Object) {
Type otherObject = Object.clone();
// do stuff to otherObject
return otherObject;
}
This is something I do quite frequently, albiet sparingly. Is there a nicer way to do this?
For example, A way to make java pass by value, instead of by reference, so that modifying the argument wouldn’t have unforseen consiquences for users of my classes.
Besides being less clear(sort of) clone methods presumably run in O(n) time, so not having to do this would be nice.
Thanks!
From a security point of view (and that usually keeps us honest),
cloneis usually the wrong thing to do (exceptHttpCookie– it’s mutable butfinal). If the object has a dodgy implementation, you’ll be copying that as well.The best thing you can do is make,
Typeimmutable. The problem goes away. No need to copy.If it is a mutable value, just construct a copy –
new Type(object)or whatever. Remember to the copying should be done before checking that the contents of the object are valid, to avoid time-of-check to time-of-use bugs (TOCTOU/TOC2TOU).