Why use a free interface?

When compared with classic properties, what is the biggest gain in use?

I know that duplicate instance name is gone, but what is it?

public class PropClass
{
  public Object1 object1 { get; set; }
  public Object2 object2 { get; set; }
}

PropClass propClass = new PropClass();
propClass.object1 = o1;
propClass.object2 = o2;

public class FluentClass
{
    public Object1 object1 { get; private set; }
    public Object2 object2 { get; private set; }

    public FluentClass SetObject1(Object1 o1)
    {
        object1 = o1;
        return this;
    }

    public FluentClass SetObject2(Object1 o2)
    {
        object1 = o2;
        return this;
    }
}

FluentClass fluentClass = new FluentClass().SetObject1(o1).SetObject1(o2);
+3
source share
4 answers

IMHO there is no big gain in setting properties with a smooth interface, especially with C # 3.0 class initializers. Free interfaces become more interesting when you start chaining methods and operations.

+6
source

It depends on how it is used. In your example, it makes no sense to use a free interface.

, , , (, / ). Test Data Builders , . , .

, , Martin Fowler .

, API-, , , /.

+2

(Builder) , . # 3.5+ , , LINQ .

public BaseControl
{
    public void RenderControl(HTMLWriter writer) {}
}

public TextBox : BaseControl
{
    public string Text { get;set; }
}

public static T TabIndex<T>(this T control, int index) where T : BaseControl {}

, , TabIndex , .

BaseControl control1 = new BaseControl();
control1.TabIndex(1);

// Moreover, you can use this for any devired controls like this
TextBox control2 = new TextBox()
{
    Text = "test"
};

// The following method still return TextBox control.
control2.TabIndex(2);

, BaseControl. , . , .

, , , .

var pmLogOnName = Html.CreatePopUpMenu("pmLogOnName")
                      .AddMenuItem("mLogOnName-RememberMe", "Remember UserName", isCheckBox: true, isSelected: true);

Html.CreateTextBox("txtLogOnName", 1)
    .BindData(Model, x => x.LogOnName, "showError")
    .WaterMark(LogOnView.LogOnName)
    .BindMenu(pmLogOnName)
+2

Not necessarily a big advantage, in my opinion, or simple classes, as you have above (classes with several properties). This is another semantics, which is more convenient for some developers, on the one hand. On the other hand, I think it is very beneficial in some arenas, such as ASP.NET MVC ... I use Telerik MVC controls that use a free interface, and it’s very nice to customize the controls; MS way requires the use of collections and anonymous classes, and it is not so convenient to use.

NTN.

0
source

Source: https://habr.com/ru/post/1726878/


All Articles