What's the point of DSLs / fluent interfaces

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

    I would say that fluent interfaces are slightly overdone and I would think that you have picked just one such example.

    I find fluent interfaces particularly strong when you are constructing a complex model with it. With model I mean e.g. a complex relationship of instantiated objects. The fluent interface is then a way to guide the developer to correctly construct instances of the semantic model. Such a fluent interface is then an excellent way to separate the mechanics and relationships of a model from the "grammar" that you use to construct the model, essentially shielding details from the end user and reducing the available verbs to maybe just those relevant in a particular scenario.

    Your example seems a bit like overkill.

    I have lately done some fluent interface on top of the SplitterContainer from Windows Forms. Arguably, the semantic model of a hierarchy of controls is somewhat complex to correctly construct. By providing a small fluent API a developer can now declaratively express how his SplitterContainer should work. Usage goes like

    var s = new SplitBoxSetup();
    s.AddVerticalSplit()
     .PanelOne().PlaceControl(()=> new Label())
     .PanelTwo()
     .AddHorizontalSplit()
     .PanelOne().PlaceControl(()=> new Label())
     .PanelTwo().PlaceControl(()=> new Panel());
    form.Controls.Add(s.TopControl);
    

    I have now reduced the complex mechanics of the control hierarchy to a couple of verbs that are relevant for the issue at hand.

    Hope this helps

提交回复
热议问题