FizzBuzz 2.0 :: Adventures in Beautiful Code

by M. David Peterson

I recently wrote an entry to my Dev.AOL blog entitled "Solving FizzBuzz in XSLT 1.0" built upon the premise that in the real world, data changes, and it's because it changes that instead of thinking of how to solve problems using static data variables, we should instead be trying to solve them in ways that are much more adaptable, and therefore, reusable.

In other words, if your desire is to find someone who truly understands how to write code that solves real-world problems, then use real-world scenarios: Data changes > You're code shouldn't have to change with it.

Of course one could argue "code? data? what's the difference?", and of course, I would only be able to agree. But none-the-less, there's still a need to write the initial processing code that will then process and transform the data code into whatever it is it needs to be transformed into, and it's on this premise I present the following as a picture perfect example of what truly Beautiful Code looks like.

After writing the initial "in XSLT 1.0" post linked above, I made a post to XSL-List with the following request,

6 Comments

Jakob
2007-03-19 14:02:42
Here's my simple solution. The only thing you need is a root element really..



















Jakob
2007-03-19 14:07:16
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:for-each select="1 to 100">
<xsl:choose>
<xsl:when test="(. mod 3) = 0"><xsl:value-of select="'fizz'"/></xsl:when>
<xsl:when test="(. mod 5) = 0"><xsl:value-of select="'buzz'"/></xsl:when>
<xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
</xsl:choose>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>


M. David Peterson
2007-03-20 04:37:33
@Jakob,


Thanks! Will add this to the AOL XSLT 2.0 solution post now.

M. David Peterson
2007-03-20 04:40:20
Done > http://dev.aol.com/blog/mdavidpeterson/2007/03/14/fizz-buzz-in-xslt-2.0#6


Thanks, Jakob!

iWantToKeepAnon
2007-04-16 14:07:39
I agree this is "Beautiful Code", but doesn't it fail the original test; i.e. dynamic code? I can't help but notice hard coded 3's, 5's, and all permutations when mod 15. Which makes the hard coding 7+ times than the "rejected" solutions.
M. David Peterson
2007-04-23 04:01:11
@iWantToKeepAnon,


Fair enough, and while I still hold true to the beautiful code part, I did recognize the choice Dimitre made to hard code the values. Can't say I know his reason, but my guess is that because of the ability to easily swap out the values for the values contained in the XML, this was either a simple oversight, or a choice to keep the code a bit more readable such that one could place focus on how the solution works as opposed to how to interpret what the values contained in the XML would be.