1

Why is programming style important?

Programming style is most important if your program is used for a while or meant for people beyond you. But it is good practice to integrate a good programming style in your everyday programming activities and routines. Active research means coming back to your code, for example, during revisions of a manuscript. If your code looks messy, going back to the analysis stage is horrible. Make your life easier. It is a sign of bad programming style, if your script/program is so comlex that only you can understand it. If everybody is able to understand it, you probably did a good job. But also remember, programming styles are not written in stone and often reflect a compromise between different rules/guidelines. In the following I describe a few basic guidelines which I consider useful (all is based on Matlab syntax).

Simple rules that improve your progamming (good on the right):

Indent code within loops and statements:

if 5 > 1

disp('Poor indent.')

end

vs.

if 5 > 1

disp('Good indent.')

end

Find the simplest coding solution:

x = [2 6 1 3];

y = 0;

for ii = 1 : length(x)

y = y + x(ii);

end

vs.

x = [2 6 1 3];

y = sum(x);

Use meaningful variable names:

tt = [25 36 21 45 19];

vs.

age = [25 36 21 45 19];

Use comments, and use verbs in comments:

age = [32 24 27 29 31 45];

mage = mean(age);

vs.

% calculate mean age

age = [32 24 27 29 31 45];

mage = mean(age);

Vertical alignment:

age = [32 24];

body_weight = [70 67]; % in kg

vs.

age               = [32 24];

body_weight = [70 67];

Other aspects to consider:

  • Build functions for repetitions
  • Check whether somebody programmmed this already
  • Find a balance between brevity and clarity
  • Build a help/documentation into your script

Other webpages provide further insight into good programming styles: wikipedia or the following list are examples of such resources.