MKII
MKII

Reputation: 911

Any way to make this more generic?

I have these two functions, used to search for a folder within a hierarchy:

public Folder<T> Find (string Path)
  {
  Folder<T> Result = null;

  if (this.Path != Path &&
      ChildrenDict != null)
    {
    foreach (KeyValuePair<long, Folder<T>> Child in ChildrenDict)
      {
      Result = Child.Value.Find (Path);
      }
    }

  else
    {
    Result = this;
    }

  return Result;
  }

public Folder<T> Find (long ID)
  {
  Folder<T> Result = null;

  if (this.ID != ID &&
      ChildrenDict != null)
    {
    foreach (KeyValuePair<long, Folder<T>> Child in ChildrenDict)
      {
      Result = Child.Value.Find (ID);
      }
    }

  else
    {
    Result = this;
    }

  return Result;
  }

As you can see, they are very similar to one another. How can I re-structure them so I don't have essentially the same code several times, one per each property I might want to use to find them?

Upvotes: 0

Views: 37

Answers (1)

DaniCE
DaniCE

Reputation: 2421

Create a method with a condition parameter which does the logic:

protected Folder<T> Find(Func<Folder<T>, bool> condition) {
    Folder<T> Result = null;
    if(!condition(this) && ChildrenDict != null) {
        foreach(var Child in ChildrenDict) {
            Result = Child.Value.Find(condition);
        }
    } else {
        Result = this;
    }
    return Result;
}

Rewrite your public Find methods as:

public Folder<T> Find(string path) {
   return Find(f => f.Path == path);
}

Upvotes: 1

Related Questions