What's the point of DSLs / fluent interfaces

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

    It's one way to implement things.

    For objects that do nothing but manipulate the same item over and over again, there's nothing really wrong with it. Consider C++ Streams: they're the ultimate in this interface. Every operation returns the stream again, so you can chain together another stream operation.

    If you're doing LINQ, and doing manipulation of an object over and over, this makes some sense.

    However, in your design, you have to be careful. What should the behavior be if you want to deviate halfway through? (IE,

    var obj1 = object.Shrink(0.50); // obj1 is now 50% of obj2
    var obj2 = object.Shrink(0.75); // is ojb2 now 75% of ojb1 or is it 75% of the original?
    

    If obj2 was 75% of the original object, then that means you're making a full copy of the object every time (and has its advantages in many cases, like if you're trying to make two instances of the same thing, but slightly differently).

    If the methods simply manipulate the original object, then this kind of syntax is somewhat disingenuous. Those are manipulations on the object instead of manipulations to create a changed object.

    Not all classes work like this, nor does it make sense to do this kind of design. For example, this style of design would have little to no usefulness in the design of a hardware driver or the core of a GUI application. As long as the design involves nothing but manipulating some data, this pattern isn't a bad one.

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