Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java language constructs to indicate that an argument won't be mutated?

I have a method that take multiple arguments, some of these arguments will be changed inside the method. Some are used as read only. The client (other parts of the code that call such a method) provide object instances as arguments.

What constructs of the java language are available that let me declare that an argument shouldn't or won't or can't be mutated inside the method. Constrcuts like annotations or keywords, that tell the client that the method won't change the objects instances used as arguments in the method call. Also constructs that would generate compilation errors or warning in case I (as an implementor of such a method) try to mutate the object accidently inside the method implementation.

I know about the keyword final but this is only to make sure that a reference is not updated.

Immutability is not a solution, as in other methods (or elsewhere in my application) I want to have instances of the type to be mutable, only within this method call, I want to give a "promise" to the client, that I won't change his instance provided as an argument.

Deep copying or cloning the argument or letting the client(caller) do such a thing is not necessary, as it is not part of the logic of the method to change the instance anyways. I just want to make to know if the language will help double check this won't happen.

like image 852
StaticBug Avatar asked Dec 24 '22 12:12

StaticBug


2 Answers

There's no way to define an argument read-only (only what you already mentioned). However, you can use the builder pattern to build the passed object so that the built object will only have getter methods, thus it won't have setter methods making it effectively immutable (note that reflection still can be used to modify its fields).

like image 142
Gergely Kőrössy Avatar answered Mar 16 '23 00:03

Gergely Kőrössy


There's no pure java solution for you there.

As you mentioned, the final keyword will only ensure no new value can be assigned to that reference.

One precaution you can use is to clone, or wrap around your mutable arguments depending on the case.

There are some (cumbersome) techniques available to deep-clone collections and maps (see here and here for quick examples within SO).

Ultimately, a well-presented and thorough javadoc can provide the appropriate level of documentation here.

like image 20
Mena Avatar answered Mar 16 '23 01:03

Mena