What's the point of DSLs / fluent interfaces

前端 未结 7 1110
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 04:11

I was recently watching a webcast about how to create a fluent DSL and I have to admit, I don\'t understand the reasons why one would use such an approach (at least for the give

7条回答
  •  后悔当初
    2021-02-01 04:36

    2 - Is this fluent interface approach just a replacement for the non existing named method parameters in C#? Would named parameters make fluent interfaces obsolete, e.g. something similar objective-C offers:

    Well yes and no. The fluent interface gives you a larger amount of flexibility. Something that could not be achieved with named params is:

    sizer.FromImage(i)
     .ReduceByPercent(x)
     .Pixalize()
     .ReduceByPercent(x)
     .OutputImageFormat(ImageFormat.Jpeg)
     .ToLocation(o)
     .Save();
    

    The FromImage, ToLocation and OutputImageFormat in the fluid interface, smell a bit to me. Instead I would have done something along these lines, which I think is much clearer.

     new Sizer("bob.jpeg") 
     .ReduceByPercent(x)
     .Pixalize()
     .ReduceByPercent(x)
     .Save("file.jpeg",ImageFormat.Jpeg);
    

    Fluent interfaces have the same problems many programming techniques have, they can be misused, overused or underused. I think that when this technique is used effectively it can create a richer and more concise programming model. Even StringBuilder supports it.

    var sb = new StringBuilder(); 
    sb.AppendLine("Hello")
     .AppendLine("World"); 
    

提交回复
热议问题