Re: Const parameter to function
- From: "Bruce Wood" <brucewood@xxxxxxxxxx>
- Date: 1 Nov 2006 11:39:44 -0800
awheeler@xxxxxxxxxxxxxxxxx wrote:
Is it possible to pass an object reference to a function and ensure
that the function is unable to modify the state of the object?
One clever alternative that was mentioned recently in another thread is
to create an interface for whatever of the object's properties / events
/ methods are required, but not include any setters in the interface
(or any methods that modify the object's state). For example:
public interface IImmutablePerson
{
int Id { get; }
string Name { get; }
}
public class Person : IImmutablePerson
{
private int _id;
private string _name;
public Person(int id, string name) { this._id = id; this._name =
name; }
public int Id { get { return this._id; } set { this._id = value; }
}
public string Name ( get { return this._name; } set { this._name =
value; } }
public void TrimName() { this._name = this._name.Trim(); }
}
public void DoSomethingWithPerson(IImmutablePerson person) { ... }
In this case, you're not _guaranteed_, but are reasonably assured that
DoSomethingWithPerson will not change anything in the Person object,
because it uses it via the interface IImmutablePerson, which doesn't
declare any property setters and doesn't include the method TrimName()
(which modifies the Name).
Now, if DoSomethingWIthPerson chose to be evil, it could always do
this:
Person mutablePerson = (Person)person;
mutablePerson.Name = "foo";
but this would clearly violate the intent of the declaration, which is
that the argument not be modified in any way.
If you truly, truly want pass-by-value at the object state level, with
full guarantees, I would say Clone that puppy, and pass the clone.
(This assumes, of course, that the object in question implements
ICloneable. Even then, the method might be able to modify objects that
are referred to by both the original object and the clone, if there are
any.)
.
- References:
- Const parameter to function
- From: awheeler
- Const parameter to function
- Prev by Date: Re: Java System.currentTimeMillis() equivalent
- Next by Date: Re: Oracle connectivity
- Previous by thread: Re: Const parameter to function
- Next by thread: Re: Overriding Key Strokes
- Index(es):
Relevant Pages
|