For those of you mingling in multiple languages it is hard to keep it all straight. Are parameters passed into functions pass-by-value? or pass-by-reference?
Let's get straight to the point. We are talking about Java here, and Java is pass by value. But I think that people are confused about what pass by value in java really means.
Let's look at an example.
public void passByValue(MyObject oParam){
oParam.myAttribute = 10;
}
called by: public static void main(String [] args)
{
MyObject oMain = new MyObject();
oMain.myAttribute = 5;
passByValue(oMain);
system.out.print(oMain.myAttribute)
}
What is the result of the system.out.print line above? If its pass by value the value should be 5, right? WRONG.
Even though Java is pass by value, this common misconception gets a lot of people. Java passes object references by value, not the objects themselves. What do I mean by that? Well let's look at how a reference works conceptually.
This is what we get when we do "MyObject oMain = new MyObject();"
Now, when we pass in "oMain" as a parameter to the function "passByValue", the value of the reference is copied to the new parameter "oParam":
Now you can see that any modifications to the "oParam" reference, is acting on the same object that the "oMain" reference is pointing to.
Things get interesting when we introduce the "new" operator into the discussion. The "new" operator allocates a new instance of an object, and sets the reference to point to that object. So say we rewrite our code above to:
public void passByValue(MyObject oParam){ oParam = new MyObject();
oParam.myAttribute = 10;
}
The result of the rewrite above will cause our original system.print line to print 5 instead of 10, since oParam changes the myAttribute of a new object instance other than the one passed in. Our diagram for this situation looks like this:
This leads into the discussion of "defensive copying". When we use the "new" operator we ensure that our method does not change the value of the object passed in. Of course, if you are passing in immutable objects, there is no need for this.
Defensive copying is often used when passing Lists.
public void passByValue(List<MyObject> list){ list = new List<MyObject>(list); // clone list
// do something with new list
}


No comments:
Post a Comment