Coding Horror

programming and human factors

When Object-Oriented Rendering is Too Much Code

Let's say you wanted to generate and render this XML fragment:

  
<status code="1" />
<data>
<usergroup id="usr" />
</data>

Here's a fully object-oriented way of building it:

  
System.Text.StringBuilder sb = new System.Text.StringBuilder();  
XmlWriterSettings xs = new XmlWriterSettings();  
xs.ConformanceLevel = ConformanceLevel.Fragment;  
xs.Indent = true;  
XmlWriter xw = XmlWriter.Create(sb, xs);  
xw.WriteStartElement("status");  
xw.WriteAttributeString("code", "1");  
xw.WriteEndElement();  
xw.WriteStartElement("data");  
xw.WriteStartElement("usergroup");  
xw.WriteAttributeString("id", "usr");  
xw.WriteEndElement();  
xw.WriteEndElement();  
xw.Flush();  
return sb.ToString();  

That seems like a tremendous amount of code to do something relatively simple. I could abandon the pure object approach and do it in two lines of code:

  
string s =  
@"<status code=""{0}"" />
<data>
<usergroup id=""{1}"" />
</data>";
return String.Format(s, "1", "usr");  

It's far less code. And it's much easier to read!

I've worked with developers who insisted that everything had to be generated through an object model, even if the object-oriented way required many times the amount of code. Although I haven't worked with Daniel Cazzulino, he typifies this attitude:

If you're using Response.Write, you're a dreadful citizen of the ASP.NET world.

As my friend Victor said, "Response.Write is there just for compatibility reasons and for old script programmers to not feel lonely".

An app written in such a way will not only be difficult to maintain and evolve, it will be almost impossible to customize (specially its layout), will never catch up with the upcoming mobile features and just hurts the eye. Everytime I see a Response.Write, and specially if it's not even kind enough to use HtmlTextWriterTag, HtmlTextWriterAttribute and HtmlTextWriterStyle, the developer who wrote it is instantly removed from my in-memory list of good ASP.NET programmers.

Like Rick Strahl, I'm not convinced the verbosity of objects like HtmlTextWriter and XmlTextWriter are warranted.

The idea of "write once, run anywhere" via a complex set of objects and adapters is a pleasant one, but it also adds a heavy burden of verbosity and complexity to your project. And you probably aren't gonna need it anyway. Sometimes it's simpler and clearer to render the HTML or XML directly to the page without all that OO cruft gunking up the works.

Written by Jeff Atwood

Indoor enthusiast. Co-founder of Stack Exchange and Discourse. Disclaimer: I have no idea what I'm talking about. Find me here: http://twitter.com/codinghorror