Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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 agree that in this case the first approach is cleaner and thus more appropriate for simple cases, but it does convey more responsibility for getting the output correct. For example, if you had to use a parameter value for the link target URL instead of a string literal, you'd need to ensure it's properly encoded (escape characters, etc.) when composing the string, whereas the HtmlAnchor class will handle that for you automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top