Hacker News new | ask | show | jobs
by mjgoeke 1684 days ago
I work in C# but have come to a similar conclusion to his note at the top of his article.

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.

1 comments

For C#, the only method chaining we really do today would be for LINQ (very heavy usage) and AspNetCore startup logic.

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;
  }