Programming Style Guide

Every programmer and programming language has a preferred variation on how to format code. Here are my best suggestions for the languages I tend to code.

  • Use spaces, not tabs. The definition (display width) of a tab can vary from one editor and platform to the next. A space is always a space.
  • Use two (2) spaces to indent a block of code.
  • Always wrap code blocks with curly braces { } even if they’re optional for a single line of code. Someone will, eventually, want to add a second line of code to the block and will, as a rule, forget to add the curly braces.
  • The opening curly brace of a block should be on the same line as its opening statement.
        public String getFirstname () {
        while (i < 5) {
  • The closing curly brace should be on its own line.
  • Leave a blank line after closing a block of code (including the end of a method), unless followed immediately by another closing curly brace.
  • Place a comment after closing a block of code when there’s a series of closing curly braces.
                } // if
              } // method
            } // class
  • always put one (1) space before and after binary operators.
        x = x + 5;
        while (i < 5) {
  • Put one (1) space before the opening parenthesis and after the closing parenthesis in statements (for, while, if, and so on) or function calls.
        for (int i = 0; i < 100; i = i + 1) {
        while (x != 2) {
        if (isPrime (n)) {
        sin (5)
        getPrice ()
  • Indent each new code block.
        for (int i = 0; i < 100; i = i + 1) {
          if ((i % 2) != 0) {
            if (isPrime (i)) {
              System.out.println (i);
            } // if
          } // if
        } // for
  • Use the variable naming convention used in your language of the moment: camelCase or under_scores.
  • Use meaningful variable and method names. For method names, verbNoun them.
        getFirstname ()
        computeSalary ()
  • Use single letter variable names iff the letter reflects a standard (recognizable) convention.
    • i, j, k for an index (counter) variable
    • x, y, z for coordinates in 3-space
    • a, b, c for coefficients
    • m, n for the number of items in a collection
    • r for the radius of a circle
    • w, h for the width and height of an object
  • Use ALL_UPPERCASE for constants (fixed values, like PI)
  • Use white space to make your code more readable.
  • Comments should describe why you’re doing something, not how. The code tells me how you’re doing it.