When creating a custom WebControl
, UserControl
, Control
and there is the need to override the various Render methods there are mainly 2 way to accomplish this:
the quick and dirty:
public override void RenderControl(HtmlTextWriter writer)
{
writer.Write("<div class=\"{0}\"><a href={1}>{2}</a>", CssClass, "/someurl.aspx", LocalizedStrings.EditLinkText);
base.RenderControl(writer);
writer.Write("</div>");
}
the long and clean:
public override void RenderControl(HtmlTextWriter writer)
{
writer.WriteBeginTag(HtmlTextWriterTag.Div.ToString());
writer.WriteAttribute(HtmlTextWriterAttribute.Class.ToString(), CssClass);
writer.Write(HtmlTextWriter.TagRightChar);
var link = new HtmlAnchor();
link.HRef = "/someurl.aspx";
link.Title = LocalizedStrings.EditLinkTitle;
link.InnerText = LocalizedStrings.EditLinkText; ;
link.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "someclass");
link.RenderControl(writer);
base.RenderControl(writer);
writer.WriteEndTag(HtmlTextWriterTag.Div.ToString());
}
I was wondering if the second method was worth it.
As a fan of Clean Code I would pick the first approach. Even if the second approach is more "by the book", it lacks the clarity of the first approach.
Source code should always convey intent in a clear manner (well, it should work too), so until proven ineffective, I would go with the first method.
I asked myself that question once when I was developing web controls. To try to resolve it I decompile a library of telerik and then I saw how they implement web controls. They develop many components and use the second approximation.
In my opinion is the best option because if the control is complex your code becomes a lot of string.format or something like that and can be difficult to understand and modify. Of course the second option may also be unclear but with very few utility methods you can create highly maintainable controls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With