Coding Style

Coding style guidelines can be used to make your code more readable.
This doesn't help the computer, but it may help you or another coder.
Here are some general observations, mostly borrowed from wiser souls:

  • Clarity is more important than conciseness.

  • Code's layout can make the structure more evident.

  • Regularity can help the brain recognize idioms, patterns, etc.

  • There are many kinds of code (eg, CSS, HTML, JavaScript);
    all of them deserve clean and thoughtful layout.

Although I generally agree with bbatsov's ruby-style-guide,
I have a few personal additions and exceptions, including:

Character Use

  • Use USASCII (ie, 7-bit) unless you expect to internationalize.
    (This is basically a form of YAGNI.)

  • Use underscores in CamelCase, eg: Camel_Case, XML_Hacks.
    (This aids in scanning and eliminates issues with acronyms.)

  • Avoid single-letter identifiers except (perhaps) in one-line blocks.

  • Avoid interpolation shorthand, eg, "#@foo #@bar"

  • Use %r for regular expressions with slashes, eg: "%r{/tmp/foo}

Comments

  • Put initial comment blocks inside the thing being described.
    (See Documentation for details and rationale.)

  • Use conventional English sentence format, eg:

    • Use proper capitalization, punctuation, etc.
    • Separate sentences with two spaces, for readability.

  • Begin certain types of comments with "findable" tags, eg:

    • #B - brittle
    • #C - connascence
    • #D - debug
    • #K - kludge
    • #P - portability
    • #T - trace
    • #TG - trace (guarded)

Miscellany

  • Avoid assignments in conditional expressions, eg: "if foo = bar"
    (It's far too easy to mistake = for ==.)

  • Prefer joining an array to assembling a string.

White Space

  • Shorten "{ |e| ... }" to "{|e| ... }".

  • Add spaces as needed for clarity, eg:

    • foo( bar[:baz] )
    • foo( bar(:baz) )
    • foo[ bar[:baz] )
    • foo[ bar(:baz) ]
    • "foo #{ bar }"

  • Add line breaks reasonably freely; they're cheap!
    (This helps the reader to spot code sections, methods, etc.)


This wiki page is maintained by Rich Morin, an independent consultant specializing in software design, development, and documentation. Please feel free to email comments, inquiries, suggestions, etc!

Topic revision: r6 - 03 Jan 2012, RichMorin
This site is powered by Foswiki Copyright © by the contributing authors. All material on this wiki is the property of the contributing authors.
Foswiki version v2.1.6, Release Foswiki-2.1.6, Plugin API version 2.4
Ideas, requests, problems regarding CFCL Wiki? Send us email