I have some data which I need to pass on to a recursive function. I want to make sure it isn’t changed within that function. How can I do this?
Consider:
static List<Person> GetPeopleWithSameNameAncestors(List<Person> people)
{
return people.Where(person => HasAncestorWithName(person.Parents, person.Name)).ToList();
}
//Here, nameToLookFor is always the same for every outside call to this function
static bool HasAncestorWithName(List<Person> lookIn, String nameToLookFor)
{
return lookIn.Any(p => p.Name == nameToLookFor || (p.Parents != null && HasAncestorWithName(p.Parents, nameToLookFor)));
}
Real situation is more complicated, that’s why it’s important to make sure nameToLookFor isn’t changed, because somebody could easily do that. Oh, and I can’t touch the “Person” class.
If this isn’t possible directly, does anybody know a pattern which could solve this problem safely?
If you are really worried about this, consider using the Decorator Pattern to wrap your Person object – but wrap it, as to make it Immutable.
Pass this object around in your code – you can easily convert the list like:
Also, use Immutable collection types, like IEnumerable instead of mutable ICollection implementations.