Fluent interfaces and leaky abstractions

前端 未结 8 2421
攒了一身酷
攒了一身酷 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:15

    A fluent interface a term Eric Evans coined and it's just another name for method chaining. Martin Fowler wrote a couple of articles on this subject, but it roughly looks like this:

    m_Window = window::with()
        .width(l_Width)
        .height(l_Height)
        .title("default window")
        .left(200)
        .top(200)
    .create();
    

    Fluent interface are generally used to create named parameters in a language that doesn't support them (the Named Parameter Idiom in C++ for example), or in Domain Specific Languages to make the code read more fluently.

    I've seen them being used for everything from image processing libraries, to regular expression libraries, 3D libraries. Other examples include the construction of tree structures, lists, or other datastructures. Everything that requires the construction of complex objects (load of parameters) can make use of Fluent Interfaces to make it more readable. For example, compare the previous example to the CreateWindow function call:

     ::CreateWindow(
          "Window class", 
          "Window title", 
          dwStyle, X, Y, 
          nWidth, nHeight, 
          hWndPant, hMenu, 
          hInstance, NULL
     );
    

提交回复
热议问题