posted
11/05/2006

order of subroutines in source code

It has been an issue how to order the functions in a source file. There are several intuitive ideas, for example, by functionality (data I/O, graphics, etc), by the level of importance/abstraction. This is a problem once the source file has been put in version control (say, Subversion) because from that point on the ordering should be kept as stable as possible, otherwise it's hard to 'diff' different versions of the file.

Alphabetic order is not feasible as one often want to change the name of functions.

I've just got some ideas while programming in R. This applies to other languages that does not have a specific requirement of the order of functions. Supposing we're at the point to add a function to an existing source file, make a decision in the following steps:

  1. Start from the beginning of the file and stop before the first function that calls this new function. If no such function is found, we end up at EOF. The new function should be put somewhere between BOF and the current point.
  2. In its permissible range, if there is a block that this new function apparently belongs to, for example, in terms of functionality (data processing, graphics, I/O, etc), put the new function in that block. If there's no clearly good spot in the block, put the new function at the end of the block.