In the past the most that I’ve ever used serialization is the automated kind that you get with web services. I’ve recently been looking into some stuff that could use the power of serialization to eliminate thousands of lines of code that is custom serializing. Today I decided to take the little bit I knew about the technical situation (some dummy left all that stuff at work) and do some exploratory coding. Here’s what I found out.
The output format that we need to generate is not something that is intuitive to programmers. Below is a snippet of what we need to see generated and most of the current development team see this and guesses at the meaning of the elements based on the data values that each element holds.
For maintainability we need to be able to provide an easy, in code translation of these values to a meaningful business nomenclature.
Current XML Generation
The above example trivializes both the size and the depth of the XML that is being generated. That complexity also leads to a great deal of confusion when you’re looking at a StringBuilder that concatenates elements and values together for a structure that is 8+ levels deep and over 10,000 characters in length. As we know more lines of code increases the chances for a developer to make a silly accidental mistake. Regardless of if you’re an ardent TDD practitioner, or if you’re performing thorough multi-person code reviews, when you’re creating string values problems like these are almost impossible to detect before they become visible in the application.
What I was playing with
Once I saw all the code that was being manually written to generate the XML, I immediately thought of some stuff I had read about serializing business objects. I was pretty sure that this would help us, but because of the depth of the embedding and the use of custom elements I wanted to create a proof of concept. I started by creating some classes that would represent multiple layers of depth and having some elements that contained many embedded elements. To translate the elements back and forth between the meaningful business names and the cryptic XML element values I employed a number of different attributes as follows:
In the end I have only one or two small concerns (I wish I hadn’t forgotten those format documents!), otherwise I think that this will be a great way to eliminate a whole bunch of brittle code and bring some meaning to the data access layer of the system. Download the sample code that I created here.