Fluent interfaces and leaky abstractions

前端 未结 8 2233
攒了一身酷
攒了一身酷 2021-02-13 14:30

What is a fluent interface? I can\'t find a good definition of this, but all I get are long code examples in a language I am not very familiar with (e.g. C++).

Also, wha

8条回答
  •  抹茶落季
    2021-02-13 15:11

    Here's a regular every-day interface:

    public interface NotFluent
    {
      void DoA();
      void DoB();
      void DoC();
    }
    

    And here's a fluent interface:

    public interface Fluent
    {
      Fluent DoA();
      Fluent DoB();
      Fluent DoC();
    }
    

    The most obvious difference is that when we return a void, we return instead an instance of the interface type. What's understood is that the interface returned is the CURRENT INSTANCE, not a new instance of the same type. Of course, this isn't enforceable, and in the case of immutable objects (like string) it is a different instance but can be considered to be the same instance only updated.

    Here are examples of their use:

    NotFluent foo = new NotFluentImpl();
    foo.DoA();
    foo.DoB();
    foo.DoC();
    
    Fluent bar = new FluentImpl();
    bar.DoA().DoB().DoC();
    

    Notice that the fluent interface is easier to use when chaining different calls. IRL, check out the Linq extension methods and how each call is designed to flow into another. None of the methods return void, even if it would be a valid result.

提交回复
热议问题