Best practice when overriding Render methods on Asp.net WebControls, UserControls, Controls

giammin picture giammin · Feb 15, 2013 · Viewed 9.5k times · Source

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.

Answer

Fredrik Holm picture Fredrik Holm · Feb 10, 2014

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.