Wednesday, July 30th, 2008

Otherwise Blow Up

By Joel Potischman

Our applications frequently need to convert XML documents between systems. While straight XSL does a great job at mapping System A’s enumerations to System B’s, I’ve found it’s very handy to include an <xsl:otherwise> to make sure mismatches are mapped to an obvious error value instead of just being quietly lost in translation.

Let’s say my homegrown candy inventory system uses numeric enumerations to indicate different types of candy, but our vendor-made candy production system uses text codes. The following XSL snippet will translate MyCandyType to VendorCandyType:

      <xsl:element name="VendorCandyType">
<xsl:choose>
<xsl:when test="MyCandyType = 100">MILKCHOC</xsl:when>
<xsl:when test="MyCandyType = 200">DARKCHOC</xsl:when>
</xsl:choose>
</xsl:element>

This works great as long as MyCandyType is 100 or 200, but if I pass in 300, VendorCandyType will be blank. Is 300 a valid enumeration? Maybe it indicates white chocolate (yuck), and I need to add that
enumeration to my XSL, or maybe my source data is just wrong. The point is, I’m trying to map between values, and throwing the source value away makes it very difficult to diagnose the problem. It’s even worse if that field is optional, because the target system will accept the input and give no indication the data was lost.

By including an <xsl:otherwise> clause that maps the unknown value 300 to the string UNKNOWN VALUE(300),
I can rest assured that schema validation in the target system will reject this value. However, I’ll still be able to see what the source value was and determine that it was the XSL that didn’t know how to deal with it. Take a look:

      <xsl:element name="VendorCandyType">
<xsl:choose>
<xsl:when test="MyCandyType = 100">MILKCHOC</xsl:when>
<xsl:when test="MyCandyType = 200">DARKCHOC</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat('UNKNOWN VALUE (', MyCandyType, ')')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:element>

My vendor system is expecting MILKCHOC or DARKCHOC. It’s not expecting UNKNOWN VALUE(300).
It will reject the input, immediately and clearly showing me the nature of the mismatch between the two systems. It might hurt, but blowing yourself up makes your bugs much easier to catch, and thus to fix.

One Response

  1. 7/30/2008
    Josh Diehl Said:

    Neat idea. Plus now I’m hungry.

Leave a Comment