Indenting, Brackets, and Comments

This isn't really a rant or a rave, just a comment on my coding style. Although I didn't know so when I started, I learned to bracket in the K&R style. Since then, my brace style has stayed K&R, but I've developed my own style of coding, which emphasizes the comments rather than the code. It only really makes sense when you use an editor that supports syntax highlighting (otherwise, the code gets a little hard to read), but since most coders out there use an editor that does, this shouldn't be an issue.

I used to comment my code like most other people do -- code on the left, comments on the right, but when I started coding professionally, and my projects became larger and larger, I realized that no matter how clean my code was, it was still extrememly difficult for someone else to see what I was doing (or for me to know what I was doing, if I was looking at something I hadn't edited in months or years). To this end, I started focusing as much on my comments as on my code.

During this time, I started playing with PHP, which has three different types of comments. Rather than picking one or the other, I decided to use each for a different type of comment: /* */ for documentation, // for code descriptions and # for debug comments. My comments are above the code they describe, and outdented. This means that the "base" level of my code is one tab in, so that comments can be outdented. Thus, a function might look like:

/**
 * function_name:
 *  This function does something.
/**/
    function function_name($foo) {
    // Load globals
        global $Foo;
    // Do something else
        bar(true);
    # old version:
    #   bar(false);
    }

I also tend to indent multiple lines of printing and SQL statements to be more visually readable:

echo "line1\n"
    ."line2";

$db->query('
    UPDATE table_x
    SET    foobar='.escape($y).',
           baz='.escape($z).'
    WHERE  zzz='.escape($a)
    );

$db->query('
    SELECT   x.a, x.b,
             y.d, y.e
    FROM     table_x AS x
        JOIN table_y AS y
          ON x.j = y.j
    WHERE    x.foo = "bar"
         AND y.bar = "baz"
    ORDER BY x.a
    ');

You'll notice that the echo statement merely lines up the beginnings of the lines, but the SQL statement lines up the statement commands. I also indent command subsections, resulting in a much more readable query.

As for spacing, I've always used 4-space tabs (why anyone would use an 8-space tab in code is beyond me), but after recent consideration, I've switched to 4 spaces. Especially since I've discovered that jEdit can now interact with the groups of spaces as if they were single characters (ease of navigation with arrow keys, and backspace/delete behavior, has been the only real reason I used tabs).

Posted on April 25th 2008