Re: Passing by reference
- From: Bruno Desthuilliers <bdesth.quelquechose@xxxxxxxxxxxxxxxxxxx>
- Date: Tue, 31 Oct 2006 22:57:55 +0100
David Veeneman a écrit :
Is passing a method argument by reference inherently dangerous?
For what definition of "dangerous" ?
I develop in the .NET environment. For a long time, I have avoided what I consider to be the dangers of passing method arguments by reference, where the method changes the object argument.
What do you mean by "changes the object" ? Calling mehods that may modify the object's state, or rebind the identifier to another object (or any undefined value) ? In the second case, there's effectively a potential danger, but I don't see anything inherently wrong with the first one.
The biggest danger, IMHO, is that you can't tell by looking at the calling object whether the argument was changed by the method:
MyClass.MyMethod(myObject);
Is it important to know if myObject's state has changed ?
So, at the first step in a method, I have deep-copied any arguments passed in that the method will modify, then passed the modified object back as a return value:
myObject = MyClass.MyMethod(myObject);
By rebinding myObject, this code implies that the 'myObject' identifier may not (and probably won't) be pointing to the same object after the method call. Which is semantically different from just passing myObject as an argument to a method call.
In the first case, I'd expect myObject to be the same object (even if in a different state) as before the call. In the second, I'd expect the identifier to point to another object, but the original object to be unchanged - so I could call MyClass.MyMethod this way:
myOtherObject = MyClass.MyMethod(myObject)
and then have myObject totally unchanged (same object, same state), and myOtherObject pointing to a distinct object.
One of the advantages of this approach is that it forces methods to limit themselves to doing just one thing.
I fail to see how... MyClass.MyMethod could as well open an internet connection, send the content of your db to the FBI, then wipe it from disk, then return myObject unmodified...
My 2 cents...
.
- References:
- Passing by reference
- From: David Veeneman
- Passing by reference
- Prev by Date: Re: Passing by reference
- Next by Date: Re: Passing by reference
- Previous by thread: Re: Passing by reference
- Next by thread: Re: Passing by reference
- Index(es):