In .Net, you can chain methods returning a value or by using a void. Is one of them the “right way”?
So you could say
1)
Foo myFoo = new Foo();
myfoo.Bars =
myBars.DoSomethingCool(x)
.DoSomethingElse(y)
.AndSomethingElse(z);
public static IList<IBar> DoSomethingCool(this IList<IBar> source, object x)
{
IList<IBar> result = //some fn(source)
return result;
}
In this case, all 3 extension methods need to return IList (the type for myFoo.Bars)
or it could also be written as
2)
myBars.DoSomethingCool(x)
.DoSomethingElse(y)
.AndSomethingElse(z);
public static void DoSomethingCool(this IList<IBar> source, object x)
{
//Modify source
source = //some fn(source)
//Don't return anything
}
in which case, the extension methods return a void, but do the work on the source object that’s coming in?
UPDATE Simon was correct in his answer that 2) won’t compile. Here is how that could be re-written:
DoSomethingCool(myBars)
.DoSomethingElse(myBars)
.AndSomethingElse(myBars);
myBars would then be changing inside the call of each method and the methods would be returning void.
1) wins. Simon correctly answered that 2) wouldn’t compile, but he did it as a comment, so I can’t gie him credit for answering. The updated solution for 2) does everything as a side effect an I can’t think of a reason why you would ever want to do that in a statically typed language.
The points made about chaining’s debugging issue are something to consider, though I find chaining to be especially useful when filtering.
mybars.FilterByHasHappyHour()is much nicer than