May 29, 2006

On XmlReader/XmlWriter design changes in .NET 2.0

From .NET 1.X experience Microsoft seems finally figured out that providing a set of concrete poorly composable XmlReader and XmlWriter implementations (XmlTextReader, XmlTextWriter, XmlValidatingReader, XmlNodeReader) and emphasizing on programming with concrete classes instead of anstract XmlReader/Xmlwriter was really bad idea. One notorious horrible sample was XmlValidatingReader accepting abstract XmlReader instance and downcasting it silently to XmlTextReader inside. In .NET 2.0 Microsoft (with a huge diffidence) is trying to bring some order to that mess:

  1. XmlReader and XmlWriter now follow factory method design pattern by providing static Create() method which is now recommended way of creating XmlReader and XmlWriter instances.
  2. While not being marked as obsolete or deprecated or not recommended, concrete implementations like XmlTextReader and XmlTextWriter are now just wrappers for internal classes used to implement Create() factory method.
  3. I was said that Microsoft will be "moving away from the XmlTextReader and XmlValidating reader" and "emphasize programming directly to the XmlReader and will provide an implementation of the factory design patterns which returns different XmlReader instances based on which features the user is interested.".

...

Well, unfortunately when you do something wrong for years you can't fix things "in a one swift stroke". Sadly, but MSDN documentation itself (even System.Xml namespace documentation!) is still full of samples using "not recommended" XmlTextReader and XmlTextWriters. And if you don't follow you words youself why would others do? Reality is that .NET developers didn't notice that shy recommendation and keep programming into concrete XML reader/writer classes.

So it wasn't a surprise for me to see fresh MSDN Magazine (06/2006) article "Five Ways to Emit Test Results as XML" promoting using XmlTextWriter class once again and not even mentioning XmlWriter.Create() pattern. Hey, I thought it's a requirement for MSDN authors to read MSDN documentation on a subject? Apparently it's not.

Another thing that bothers me is that XmlReader/XmlWriter factory has no extensibility points whatsoever. So that's not an option for non-Microsoft XML parsers and writers like XIncludingReader or MultiXmlTextWriter to be created in that factory. There is no way to plug in support for XML Base into a system without writing actual code that instantiates XmlBaseAwareXmlTextReader. Microsoft still considers providing abstract factory for XML readers/writers too geeky and similar (in terms or weirdness) to providing abstract factory for string class. Well, it probably would take another couple of .NET versions to grow up before .NET would come to extensibility Java already has for years.