Frage

Going back to the basics, I would like to know in detail the significance of the below code over the latter .. or vice versa ..

Code sample1:

<xsl:template match="Gender">
   <xsl:copy>
       <xsl:if test=".='M'">
           <xsl:text>Male</xsl:text>
       </xsl:if>
       <xsl:if test=".='F'">
           </xsl:text>Female</xsl:text>
       </xsl:if>
   </xsl:copy>
</xsl:template>

Code sample2:

<xsl:template match="Gender[.='M']">
   <xsl:copy>
       <xsl:text>Male</xsl:text>       
   </xsl:copy>
</xsl:template>
<xsl:template match="Gender[.='F']">
   <xsl:copy>
       <xsl:text>Female</xsl:text>       
   </xsl:copy>
</xsl:template>

I could use <xsl:choose/> instead in code1, that's not the point .. I would like to discuss on how wise is to use different templates with matching conditions over usage of if and else conditions .. considering the Performance, readability and maintenance and many more factors?

War es hilfreich?

Lösung

I would definitely prefer Code2:

  1. Simpler -- the explicit conditional instructions are gone.

  2. Shorter -- because of the above.

  3. Easier to understand -- because of 1. and 2. above.

  4. Easier to maintain: If something needs to be changed in the handling of "F" there is no chance to screw up with the handling of "M".

  5. Much more easier to extend. If Code2's stylesheet is imported into another, it is possible to override just one of the two templates -- with Code1 the whole monolithic template will need to be overridden and some code will possibly be just replicated without any change.

Remember the KISS principle: Keep It Simple, Stupid ... :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top