Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to modify an object passed to a method

Tags:

java

After passing an object into a method, I would like to change one of its fields. What's the best practice to do this task in Java?

like image 959
user496949 Avatar asked Mar 04 '11 10:03

user496949


People also ask

What happens when you pass an object to a method?

When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference.

How do you modify an object in Java?

After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.

How do you pass an object to another method?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

How object are passed to the method in Java?

Java objects are passed by reference. Means when you create a object and assign it to a reference(variable) its address is assigned to it.. and when you modify this in the called function it modifies the same object passed.


1 Answers

Simple answer

As stated in other answers, you can simply call the setter method.

More philosophical answer

Generally, it can be dangerous to mutate objects in a scope other than that in which they were created:

http://en.wikipedia.org/wiki/Functional_programming

That said, there are often times where you simply want to encapsulate bits of logic in the same logical scope where you would want to modify values of an object passed in. So the rule I would use is that as long as all calling code is fully aware of such mutations, you can call the setter method on the object (and you should create a setter method if you don't have one) in the method to which you're passing the object.

In general, if you call a function that mutates parameters from multiple places in your codebase, you will find that it becomes increasingly error prone, which is why functional programming pays off.

So, the moral of the story is: if your caller(s) are fully aware of such mutations, you could change the value in your method, but in general you should try to avoid it and instead change it in the scope in which it was created (or create a copy).

like image 59
kvista Avatar answered Sep 26 '22 12:09

kvista