0

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

  1. Create an immutable class and pass it as a parameter
  2. Deep copy the object and send the cloned object to the method.

Is there any better apporach to safeguard the method parameters?

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
HJK
  • 1,382
  • 2
  • 9
  • 19
  • 2
    Option one should be the obvious choice. If your instance can have state changes then use *defensive copies* (option 2). I don't see any harm in those approaches – TheLostMind Mar 07 '16 at 06:53
  • As suggested option 1 seems to be good. But just want to know any good approach with minimal code changes at caller end (if the method called from numerous places). In Option 2, caller is enforced to made the change (deep copy the object). I am just looking to make something at the called end rather enforcing caller to code more lines. – HJK Mar 07 '16 at 07:02
  • Like TheLostMind, I strongly suggest option 1. If you are able to make `MyClass` immutable, you don't have to worry anymore for an instance beeing altered somewhere by the caller. – Spotted Mar 07 '16 at 07:06
  • Well, if you are leaking the reference out of the scope, then it is your duty to create a *defensive copy* :P – TheLostMind Mar 07 '16 at 07:06
  • 1
    @Spotted - Also *immutable* instances will improve performance – TheLostMind Mar 07 '16 at 07:06
  • I don't really get the point how immutable instances can improve performance though it really solves concurrency issues, and also leads to much cleaner programming. Probably because it allows parallelism. – Bunti Mar 07 '16 at 07:15
  • @Bunti - C2 JIT compiler can do lot of optimizations. – TheLostMind Mar 07 '16 at 08:06

0 Answers0