by mjgoeke · 5y ago · 0 comments
C# supports extension methods, so if you want you can augment the original 3rd party class with your own (chaining in this case) methods. Or author your own “fluent interface” on your own classes, as he’s done here.
I’m the end, most of the time I found I was wanting a function ‘forward composition’ operator (like F#’s |> ). And the only place the chaining methods really made sense was factory classes/methods for complex declarative configuration.
The only ones that stuck for us were ORM mapping declarations, and factories for setting up complex domain specific data setup in tests.
If you are super addicted to certain language sugar like object initializers, then wrapping some of your business logic (e.g. mappers) with extension methods is not a terrible path. E.g.:
public Thing MyFavoriteThing => new Thing
{
Id = Guid.NewGuid(),
TheThing = _someLocalProperty.SomeTransform().Trim(),
MyOtherInitalizedFact = true
};
The alternative would look something like: public Thing MyFavoriteThing()
{
var result = new Thing
{
Id = Guid.NewGuid(),
TheThing = SomeTransform(_someLocalProperty),
MyOtherInitializedFact = true
};
result.TheThing = Trim(theThing);
return result;
}