Chapter 3. Programming Style

Table of Contents
Spacing and Formatting
Indentation
Choice Of Control Structures
Size of a Function

The one and only general guideline to good programming style is: "Make it clear!" And one might extend that to "Make it clear; first of all to you and then to the poor person that takes over your project." Every possible style feature of the language should be used to express the meaning of the code clearly.

Spacing and Formatting

Although often underestimated, the format, i.e. the visual layout of the source code itself can greatly help in the understanding of the actions described therein.

Intra-Expression Spacing

We often run into code like this

    x=a*c+(x-y)^2*b

This is not bad, especially when typed at the command line for one-time use. But the expression is not as helpful to its understanding as could be. E.g. it can be improved by making the the precedence levels of the operators stand out.

    x = a*c + b*(x-y)^2

Now, the assignment is intuitively clear at first glance. We use word "intuitive" here to make the reader alert of the consequences of formatting an expression the wrong way. Then our intuition will mislead us, as in

    x = a * c+(x-y)^2*b

Line Breaking

Breaking a long expression into lines can improve the readability dramatically. It is particularly recommended for matrix definitions with the square bracket operator. See also the section called Vector Construction in Chapter 2.

    m1 = [ 1+%i  -1+%i; ..
          -1+%i   1-%i ]

is superior to

    m1 = [1+%i -1+%i; -1+%i 1-%i]

If an arithmetic expression is split into lines the operator at which the split occurs always goes onto the next line. Preferred break points occur right before operators of equal precedence.

    d2 = fact * (a/(a+d)*(b*(1-delta) + d*delta) - d) * (P./K).^theta

becomes for example

    d2 = fact * (a/(a+d)*(b*(1-delta) + d*delta) - d) ..
         * (P./K).^theta

or

    d2 = fact ..
         * (a/(a+d)*(b*(1-delta) + d*delta) - d) ..
         * (P./K).^theta

or more dramatic

    d2 = fact ..
         * ( ..
                a / (a+d) * (b*(1-delta) + d*delta) ..
                - d ..
           ) ..
         * (P./K).^theta

The last way of breaking the expression is very LISP-like.

Setting Brackets Apart

If spaces right inside the parentheses or brackets of an expressions make the subexpression stand out more clearly, they should be used. That way

    B(k) = a1 * exp(-b1*P(k)/K(k) + b2*Q(k)/K(k))

becomes

    B(k) = a1 * exp( -b1*P(k)/K(k) + b2*Q(k)/K(k) )