XML Comments Not Programmer-Friendly
Many technologies (e.g. XSLT, XML Schema and Ant build files), require the creation of complex XML documents. The complexity of these technologies mandates good comments in order to keep the documents maintainable. These technologies are demanding and it is not trivial to create documents that work as expected. Typically, a developer will create a document, test whether it works, adjust the document, test again and so on. This interactive programming style requires the ability to temporarily comment out passages of the document. So, comments are needed for two purposes:
- Add explanations to code.
- Comment out code.
This post explains that XML comments do not meet these two requirements well. It contrasts XML with Java and shows that Java comments are more programmer-friendly:
XML has only one kind of comment:
- Starting with
<!--and ending with-->.
You cannot easily comment out code that already contains comments:
<!–
<xsl:template match=”widget”>
<!– Calculate foo as sum of bar and baz. –>
<xsl:variable name=”foo” select=”@bar + @baz”/>
</xsl:template>
–>
This does not do what you might expect. Only the bold part is commented-out. The final --> is mismatched. Also, the comment contains the illegal character sequence --. The above XML snippet is not even well-formed XML.
Java, on the other hand, has two kinds of comments:
- Traditional comments starting with
/*and ending with*/. - End-of-line comments starting with
//and extending to the end of the line.
You can easily comment out a block of code - even if that code already contains comments. Code that contains only end-of-line comments can be commented out using either traditional comments like this:
/*
public int getFoo() {
// Calculate foo as sum of bar and baz.
return bar + baz;
}
*/
Or end-of-line comments can be used like so:
// public int getFoo() {
// // Calculate foo as sum of bar and baz.
// return bar + baz;
// }
Typing all these // characters can be tedious, but most modern editors and IDEs will do it automatically. See this page for the respective commands in Eclipse.
If you want to comment out a piece of code that already uses traditional comments, you have to use the second method (end-of-line comments):
// public int getFoo() {
// /* Initialize transdimensional machinery. */
// init();
//
// // Calculate foo as sum of bar and baz.
// return bar + baz;
// }
Conclusion: XML-based technologies would be easier to work with if XML had end-of-line comments like Java does.