2008-09-24

using(TricksToFormatYourCodeNicely)

I've been writing a data importer which takes a specific data input format and outputs XML, this XML is then imported within my application. What annoyed me was the way in which the source code was formatted....


writer.WriteStartElement("data");
writer.WriteAttributeString("1", "1");
writer.WriteAttributeString("2", "2");
writer.WriteAttributeString("3", "3");

writer.WriteStartElement("systemData");
writer.WriteAttributeString("a", "a");
writer.WriteAttributeString("b", "b");
writer.WriteEndElement();//systemData

writer.WriteEndElement();//data


It just didn't look nice. I thought about splitting it into separate methods, but most of the time this would have been overkill as the methods would have been very short. Instead I wrote an extension method on XmlWriter:


public static class XmlWriterHelper
{
  public static IDisposable StartElement(this XmlWriter writer, string elementName)
  {
    return new DisposableElementWriter(writer, elementName);
  }

  private class DisposableElementWriter : IDisposable
  {
    private XmlWriter Writer;

    public DisposableElementWriter(XmlWriter writer, string elementName)
    {
      Writer = writer;
      Writer.WriteStartElement(elementName);
    }

    public void Dispose()
    {
      Writer.WriteEndElement();
    }
  }
}



Now I can write code like this instead:

using (writer.StartElement("data"))
{
  writer.WriteAttributeString("1", "1");
  writer.WriteAttributeString("2", "2");
  writer.WriteAttributeString("3", "3");
  using (writer.StartElement("systemData"))
  {
    writer.WriteAttributeString("a", "a");
    writer.WriteAttributeString("b", "b");
  }//systemData
}//data



Less code AND easier to read. What a bonus!

No comments: