Re: [xsl] Is XPath and/or XSLT designed such that I should never have to write special case code?

Subject: Re: [xsl] Is XPath and/or XSLT designed such that I should never have to write special case code?
From: "Michael Kay mike@xxxxxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Wed, 23 Jun 2021 08:13:09 -0000
> I don't think that, using an "if" (xsl:if / xsl:choose in XSLT, "if" in
XPath) control flow mechanism in the code (and equally well in XSLT) is always
a bad idea. It's an integral programming tool to solve problems. To have code
look nicer, may be we can encapsulate the "if" logic within a function.
>


I agree.

I think Roger's question is much too broad to give a general answer. But let's
take a specific example. In XSLT 1.0 you often see code that does

<xsl:for-each select="item">
  <xsl:value-of select="."/>
  <xsl:if test="position() != last()">
    <xsl:text>, </xsl:text>
  </xsl:if>
</xsl:for-each>

That's special case code to handle the last item in a list. In 2.0 we
introduced the separator attribute, so this becomes

<xsl:value-of select="item" separator=", "/>

So yes, we made a language design change to reduce your need to write
special-case code.

But "never have to write special case code"? No, that's much too strong. There
will always be a need for special case code. Programming is all about handling
the variety of inputs that can occur, and some of these input conditions can
reasonably be described as special cases.

In terms of language design, I recall a principle articulated by a guy I
admired called Henry Cosh, who designed the 4GL used by most of ICL's
mainframe customers. In fact it was a pair of principles:

(a) the language should provide high-level stereotype operations for all
sufficiently common tasks and patterns of tasks

(b) if your requirements change so your task no longer fits the stereotype,
you should only have to rewrite the part of your code that relied on the
stereotype.

The "separator" attribute is an example of a stereotype. But if your
requirements change (for example if you need to output "Smith, Jones, and
Baker" rather than "Smith, Jones, Baker") then your rewrite is confined to the
xsl:value-of instruction that uses the stereotype - you don't have to rewrite
the whole application in a different programming language.

Is producing the output "Smith, Jones, and Baker" a sufficiently common task
that it it justifies a language stereotype, e.g. providing a different value
for the last separator in a list? That's a value judgement. I would say,
probably not: you're going to have to write special case code for this one. At
that level of specialisation, it's more important for the language to provide
building blocks (functions, template rules) that enable users to construct
their own reusable code libraries.

Michael Kay
Saxonica

Current Thread