Tips for writing fluent interfaces in C# 3

前端 未结 8 1708
借酒劲吻你
借酒劲吻你 2020-12-07 11:39

I\'m after some good tips for fluent interfaces in C#. I\'m just learning about it myself but keen to hear what others think outside of the articles I am reading. In particu

相关标签:
8条回答
  • 2020-12-07 12:04

    I too am just jumping on learning how to write a fluent interface for a small app at work. I've asked around and researched a little and found that a good approach for writing a fluent interface is using the "Builder pattern", read more about it here.

    In essence, this is how I started mine:

    public class Coffee
    {
        private bool _cream;
        private int _ounces;
    
        public Coffee Make { get new Coffee(); }
    
        public Coffee WithCream()
        {
            _cream = true;
            return this;
        }
    
        public Coffee WithOuncesToServe(int ounces)
        {
            _ounces = ounces;
            return this;
        }
    }
    

    Here's a cross post to a similar question I have for implementing a closure in a fluent interface.

    0 讨论(0)
  • 2020-12-07 12:05

    On your 4th point;

    Yes I think that a complex fluent interface can still be fluent.

    I think fluent interfaces are somewhat of a compromise. (although a good one!) There has been much research into using natural language for programming and generally natural language isn't precise enough to express programs.

    Fluent interfaces are constructed so that they write like a programming language, only a small subset of what you can express in a natural language is allowed, but they read like a natural language.

    If you look at rhino mocks for example the writing part has been complicated compared to a normal library. I took me longer to learn mostly due to the fluent interface but it makes code a lot easier to read. Because programs are usually written once and read a lot more than once this is a good tradeoff.

    So to qualify my point a bit. A fluent interface that's complex to write but easy to read can still be fluent.

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