Monday, February 8, 2010

Chaining Methods - A Simple Scenario

Assuming that you are interested in training animals, let us start with a simple ITrainable interface. :)

public interface ITrainable
{
ITrainable Train(string skill);
ITrainable Do(string skill);
}

Well, nothing fancy there. Let us go ahead and create a Dog Class, which implements this interface. The only interesting piece you may find in the Dog class is, all methods are returning a type of ITrainable. As long as our Dog class implements ITrainable, we can return 'this', i.e the current Dog Instance.

public class Dog : ITrainable
{
public string Name { get; set; }
public List Skills { get; set; }

public Dog(string name)
{
Console.WriteLine();
Console.WriteLine("Dog " + name +
" created");

Name = name;
Skills = new List();
}
public ITrainable Train(string skill)
{
Console.WriteLine("Dog " + Name +
" learned " + skill);
this.Skills.Add(skill);
return this;
}

//Let us ask the dog to perform this skill
public ITrainable Do(string skill)
{
if (Skills.Contains(skill))
Console.WriteLine("Dog " + Name +
" is doing " + skill);
else
Console.WriteLine("Dog " + Name +
": Don't know how to " + skill);

return this;

}


Now, we are ready to train our Dog fluently.

//Train one dog, Hope your name is not Bobby ;)
var dog = new Dog("Bobby");
dog.Train("Running").Train("Eating")
.Do("Running").Do("Eating");



As you can see, we are chaining the method calls, because in each call, we are returning an object of type ITrainable. You'll see what Bobby is doing in the console

Dog Bobby created
Dog Bobby learned Running
Dog Bobby learned Eating
Dog Bobby is doing Running
Dog Bobby is doing Eating

No comments:

Post a Comment