Code that looks like its result

From the same Lisp tutorial I’m reading:

This “back-quoting” technique is a great feature in Lisp- it lets us write code that looks just like the data it creates. This happens frequently with code written in a functional style: By building functions that look like the data they create, we can make our code easier to understand and also build for longevity: As long as the data doesn’t change, the functions will probably not need to be refactored or otherwise changed, since they mirror the data so closely. Imagine how you’d write a function like this in VB or C: You would probably chop the path into pieces, then append the text snippets and the pieces together again- A more haphazard process that “looks” totally different from the data that is created and probably less likely to have longevity.

This is one of the things I’ve always liked about XSLT. The template rules directly show the XML that is being created. Attribute value templates (AVTs) are helpful in this regard too. In fact, I try to use them whenever possible. I try to avoid using xsl:attribute (unless there’s no other way to do it, i.e. when the attribute’s presence is conditional). For example, when you have to use an instruction to get an attribute’s value, this may seem the most natural approach:

<para>
  <xsl:attribute name="lang">
    <xsl:apply-templates mode="get-lang-value" select="."/>
  </xsl:attribute>
  ...
</para>

But I far prefer this approach even if it does take a few more characters:

<xsl:variable name="lang">
  <xsl:apply-templates mode="get-lang-value" select="."/>
</xsl:variable>
<para lang="{$lang}">
  ...
</para>

That way, when reading the code to figure out what it does, your eye can just skip by the variable definition (it’s just a variable; it doesn’t do anything). After that, it’s easy to see what we’re creating. The first example requires you to look more closely and to think about it for a second, ugh.

Now this is just a small version of a much bigger problem with understanding XSLT stylesheets, especially ones that use a lot of template rules. They can be so dynamic that you absolutely must see an example source document (input data) to understand what the stylesheet does. Integrating dynamic execution profiles into development via multiple code views and software visualization—those are some of my research interests…

Leave a Comment