Thoughts on programming

March 26th, 2009

Many programming techniques are quite complicated, but there are also some simple rules that might improve everybodies code:

Rule 1: Don’t copy code.

Everybody knows this, but how comes I find copied code almost everytime I review some project? One of the reason might be that not-copying code is a simple rule, but not an easy thing to do. Many technologies have been invented to help with this task, firstmost functional abstraction, and also Command Pattern, generics, frameworks, Aspect oriented programming etc. Still sometimes its hard, and in this situations I recommend: Find someone and talk about it, and find a solution. One of the biggest benefits of pair programming might be that it prevents copied code – you seldom commit crimes if someone is watching.

Rule 2: Minimize nesting

In respect to indentation, your code wants to be as left as possible.

Compare this code:

Version 1:

    if (myVariable.isValid())
    {
        doSomething();
        ...
        doSomethingMore();
    }
    else
    {
        throw new InvalidValueException();
    }

Version 2:

    if (!myVariable.isValid())
    {
        throw new InvalidValueException();
    }
    doSomething();
    ...
    doSomethingMore();

Version 2 is better IMHO. If you can get rid of e.g. an else, do it. This often leads to code that checks for errors/special conditions first, and makes a shortcut return (e.g. exception).

Rule 3: Don’t use abbreviations

While long names might be annoying, abbreviations come from hell. You want someone not familiar with your domain and code to understand it at a glance. Don’t let anyone puzzle if the “no” stood for “not” oder “number”.

Note that long names often signalizes that a class/method/variable hasn’t a clear purpose. I will prefer a long name over an abbreviation anyway.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

One Response to “Thoughts on programming”

  1. Paule on March 27, 2009 08:55

    Re: Rule 2. Another great way of reducing nesting is to use logical arrays and vectorization (= vector algebra) of data arrays, e.g. in Matlab:

    Version 1:

    for ii = 1:size(a,1)
    for jj = 1:size(a,2)
    if a(ii,jj) > 5
    a(ii,jj) = sqrt(a(ii,jj));
    end
    end
    end

    Takes the square root of all elements in an array whose value is greater than 5. Much faster to use the vectorized approach…

    Version 2:

    b = a > 5;
    a(b) = sqrt(a(b));

    Cool.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

Trackback URI | Comments RSS

Leave a Reply

Name (required)

Email (required)

Website

Speak your mind