I want to safe guard my method parameters that were passed to the called method from being changed accidentally. I know that we can use final
keyword to achieve this (partially) like the following in the method signature.
public void someMethod(final int intVal, final MyClass myobj){}
With the help of the above signature I cannot change the value of intVal
, but however I can change the values (members) of myobj
(I can safe guard only the reference not being changed, but not the members of the referencing object, that why I said partial).
Now I am looking to safe guard my myobj
members either, getting changed in the called method someMethod
.
In my knowledge I could achieve this using the following ways
- Create an immutable class and pass it as a parameter
- Deep copy the object and send the cloned object to the method.
Is there any better apporach to safeguard the method parameters?