Reputation: 157
I've been working away (http://tinyurl.com/m4hzjb) on this Fluent API for instantiating ASP.NET controls and feel I now have something that appears to work well. I'm looking for some feedback and opinions... good, bad or indifferent. Would you find this useful? Any technical issues you foresee? Room for improvement?
Here's a very basic usage sample for creating a standard TextBox control. Only two properties/methods are implemented, but API could easily be expanded to support full property feature set of control(s).
USAGE
Factory.TextBox()
.ID("TextBox1")
.Text("testing")
.RenderTo(this.form1);
// The above TextBox Builder is functionally same as:
TextBox textbox = new TextBox();
textbox.ID = "TextBox1";
textbox.Text = "testing";
this.form1.Controls.Add(textbox);
// Or:
this.form1.Controls.Add(new TextBox {
ID = "TextBox1",
Text = "testing"
});
Here's the full ControlBuilder class.
BUILDER
public partial class Factory
{
public static TextBoxBuilder TextBox()
{
return new TextBoxBuilder(new TextBox());
}
}
public abstract class ControlBuilder<TControl, TBuilder>
where TControl : Control
where TBuilder : ControlBuilder<TControl, TBuilder>
{
public ControlBuilder(TControl control)
{
this.control = control;
}
private TControl control;
public virtual TControl Control
{
get
{
return this.control;
}
}
public virtual void RenderTo(Control control)
{
control.Controls.Add(this.Control);
}
public TBuilder ID(string id)
{
this.Control.ID = id;
return this as TBuilder;
}
}
public abstract class TextBoxBuilder<TTextBox, TBuilder> : ControlBuilder<TTextBox, TBuilder>
where TTextBox : TextBox
where TBuilder : TextBoxBuilder<TTextBox, TBuilder>
{
public TextBoxBuilder(TTextBox control) : base(control) { }
public TBuilder Text(string text)
{
this.Control.Text = text;
return this as TBuilder;
}
}
public class TextBoxBuilder : TextBoxBuilder<TextBox, TextBoxBuilder>
{
public TextBoxBuilder(TextBox control) : base (control) { }
}
Upvotes: 0
Views: 662
Reputation: 1804
I love how Fluent APIs work, and this might be a nice way to configure dynamic controls.
I have the following points:
Ultimately, I have to say good for you to take this on. It's a great exercise, and someone may use it. Make it open source, and in a few years it might become standard.
Upvotes: 0
Reputation: 564433
I question the need here. To me, this:
Factory.TextBox()
.ID("TextBox1")
.Text("testing")
.RenderTo(this.form1);
Is far less clear than:
this.form1.Controls.Add(new TextBox {
ID = "TextBox1",
Text = "testing"
});
What is Factory? What happens if we forget the "RenderTo" line?
The first is not nearly as obvious to me, and going to be less maintainable, since it would be very difficult to extend this for custom controls (where you don't know the properties in advance), etc.
Upvotes: 3