yarffaJ nalA (jnala) wrote in lj_dev,
yarffaJ nalA

HTML in strings

Update: Changed some wording, added trailing clarification.

This is a point of style, but IMHO HTML tags should rarely be in strings in source code. Instead, it's usually preferable to use functions or object methods to generate tag pairs. This is because

  • It eliminates potential errors in quoting
  • It eliminates potential errors failing to close tags
  • It makes more of the program subject to compile-time verification
  • It allows for easier use of non-interpolatable values in the generated HTML
  • It makes use of whitespace and indentation for readability more convenient
  • It takes advantage of syntax support (highlighting and indentation) in the editor
For example, I believe that

could be better written as

Note that nothing has to be quoted, the computation of $span can be replaced with the result of a sensible function call (which could not be interpolated in a string), the editor can easily indent and highlight the code for readability, and any error in closing tags that the editor didn't pick up would be detected at compile-time. The constant references to $xg, an XML::Generator object, are somewhat unsightly; they could be eliminated, but at the expense of cluttering the LJ namespace with functions with names like "a" and "b". (I've erred on the side of caution here.)

Clarification: I'm not trying to declare that anyone else needs to do this. However, it's a nonobvious technique which has, for me, significantly reduced debugging time and improved my ability to read and maintain existing code, after a very short learning curve. I would recommend it to others, and unless Brad screams bloody murder, I'll be using it in my modifications to the LJ server code.


  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded