What's the point of DSLs / fluent interfaces

前端 未结 7 1123
爱一瞬间的悲伤
爱一瞬间的悲伤 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:48

    Consider:

    sizer.ResizeImage(inputImage, outputImage, 0.5, ImageFormat.Jpeg);
    

    What if you used less clear variable names:

    sizer.ResizeImage(i, o, x, ImageFormat.Jpeg);
    

    Imagine you've printed this code out. It's harder to infer what these arguments are, as you don't have access to the method signature.

    With the fluent interface, this is clearer:

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

    Also, the order of methods is not important. This is equivalent:

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

    In addition, perhaps you might have defaults for the output image format, and the reduction, so this could become:

     sizer.FromImage(i)
     .ToLocation(o)
     .Save();
    

    This would require overloaded constructors to achieve the same effect.

提交回复
热议问题