Creating API that is fluent

后端 未结 9 911
忘掉有多难
忘掉有多难 2020-11-28 03:35

How does one go about create an API that is fluent in nature?

Is this using extension methods primarily?

相关标签:
9条回答
  • 2020-11-28 04:15

    What is a fluent API

    Wikipedia defines them here http://en.wikipedia.org/wiki/Fluent_interface

    Why Not to use a fluent interface

    I would suggest not implementing a traditional fluent interface, as it increases the amount of code you need to write, complicates your code and is just adding unnecessary boilerplate.

    Another option, do nothing!

    Don't implement anything. Don't provide "easy" constructors for setting properties and don't provide a clever interface to help your client. Allow the client to set the properties however they normally would. In .Net C# or VB this could be as simple as using object initializers.

    Car myCar = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };
    

    So you don't need to create any clever interface in your code, and this is very readable.

    If you have very complex Sets of properties which must be set, or set in a certain order, then use a separate configuration object and pass it to the class via a separate property.

    CarConfig conf = new CarConfig { Color = Color.Yellow, Fabric = Fabric.Leather };
    Car myCar = new Car { Config = conf };
    
    0 讨论(0)
  • 2020-11-28 04:20

    Writting a fluent API it's complicated, that's why I've written Diezel that is a Fluent API generator for Java. It generates the API with interfaces (or course) to:

    1. control the calling flow
    2. catch generic types (like guice one)

    It generates also implementations.

    It's a maven plugin.

    0 讨论(0)
  • 2020-11-28 04:24

    No and yes. The basics are a good interface or interfaces for the types that you want to behave fluently. Libraries with extension methods can extend this behavior and return the interface. Extension methods give others the possibility to extend your fluent API with more methods.

    A good fluent design can be hard and takes a rather long trial and error period to totally finetune the basic building blocks. Just a fluent API for configuration or setup is not that hard.

    Learning building a fluent API does one by looking at existing APIs. Compare the FluentNHibernate with the fluent .NET APIs or the ICriteria fluent interfaces. Many configuration APIs are also designed "fluently".

    0 讨论(0)
提交回复
热议问题