Often, programmers write code that generates other code.
(The technical term is metaprogramming, but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.)
One area I find challenging is coming up with techniques to ensure that both the hand-written source file, and the computer-generated object file are clearly indented to aid debugging. The two goals often seem to be competing.
I find this particularly challenging in the PHP/HTML combination. I think that is because:
- there is sometimes more of the HTML code in the source file than the generating PHP
- HTML files tend to be longer than, say, SQL statements, and need better indenting
- HTML has space-sensitive features (e.g. between tags)
- the result is more publicly visible HTML than SQL statements, so there is more pressure to do a reasonable job.
What techniques do you use to address this?
Edit: I accept that there are at least three arguments to not bothering to generate pretty HTML code:
- Complexity of generating code is increased.
- Makes no difference to rendering by browser; developers can use Firebug or similar to view it nicely.
- Minor performance hit - increased download time for whitespace characters.
I have certainly sometimes generated code without thought to the indenting (especially SQL).
However, there are a few arguments pushing the other way:
- I find, in practice, that I do frequently read generated code - having extra steps to access it is inconvenient.
- HTML has some space-sensitivity issues that bite occasionally.
For example, consider the code:
<div class="foo">
<?php
$fooHeader();
$fooBody();
$fooFooter();
?>
</div>
It is clearer than the following code:
<div class="foo"><?php
$fooHeader();
$fooBody();
$fooFooter();
?></div>
However, it is also has different rendering because of the whitespace included in the HTML.