There are a number of approaches to stopping a method making changes to an object passed as a parameter:
- Make a copy of the object, and pass the copy. There are a variety of ways of copying objects. Copy constructors and static factory methods are probably better than implementing
clone().
- Create a read-only wrapper class for the object's class, instantiate it and pass it. The read-only wrapper either doesn't provide the update methods, or implements them to do nothing, or throw exceptions.
- Refactor the object's API so that it has an read-only interface and a read-write interface, and pass it as an instance of the former. (Of course, the caller can try to cast it to the latter ...)
- Use Java security to prevent unwanted updates. (This is expensive and complicated ...)
Of course, if the object that you are trying to "protect" has deep structure that you want to prevent changes to, then you need to make sure that you deal with this; e.g. by deep copying, by returning copies of component objects or returning them wrapped, and so on.
Most of the approaches above add complexity and runtime cost, so my advice is to avoid designs where you need to do this kind of thing. If feasible, simply document that the object should be treated as read-only, and leave it to the common sense of the person who codes the method to do the right thing.
For example, it is a well known fact that you should not change the state of an object used as a key in a Map in such a way that its value changes. However, it is common to do nothing to try to "enforce" this; i.e. to use mutable objects as keys ... and just not change them.