I have a recursive method that builds a tree-like structure of a resource and its related resources.
For each resource that I work with I add it to a class member list which I check on each iteration to make sure that we don’t loop infinately on resources that are inter dependent.
Each time I call this recursive method for the first time, I need the class member list to be clear.
At the moment I have a seperate method to do this which I can call between calls to the recursive method.
I’d like to get rid of this method call and reset the list automatically each time.
At the moment I can see two options to solve this problem:
- Test whether the calling method is the same as the currently
executing method and if not, reset the list - Get rid of the recursion and queue items instead, dequeueing and
enqueueing as we go. At the end of the method call I can reset the list.
How would you go about solving this problem? What approach would you take?
Here’s how my code currently looks:
public class GetAllRelatedResourcesByParentGuidQuery : IGetAllRelatedResourcesByParentGuidQuery
{
private readonly IList<Guid> _itemsCheckedForRelations = new List<Guid>();
public IEnumerable<IDependency> Invoke(Guid parentCiId,
IResoucesByIdQuery getResources)
{
if (!_itemsCheckedForRelations.Contains(parentCiId))
{
var relatedResources = getResources.Invoke(parentCiId);
_itemsCheckedForRelations.Add(parentCiId);
if (relatedResources.Count() > 0)
{
foreach (var relatedResource in relatedResources)
{
relatedResource.Resource.DependentResources = Invoke(
relatedResource.Resource.Id,
getResources);
yield return relatedResource;
}
}
}
}
public void ResetCheckedItemsCollection()
{
_itemsCheckedForRelations.Clear();
}
}
I would make a public method which performs the creation, but make the recursive method not care, and take it as a parameter.