next up previous contents
Next: Data Structures Up: C Programming for Research. Previous: Indentation and Commenting   Contents

Modularity and Functions

Modularity is important, code should be proceedurised by splitting complex algorithms into self contained parts which have conceptual relevance. This aids with program understanding. Also, write functions for pieces which can be re-used in several places, this will reduce both the total quantity of software and the possibility of bugs (LESS CODE $>$ LESS BUGS). This (when done properly) should result in small numbers of function parameters. If a large number seem to be required consider whether they are really necessary of if they would be sensibly encapsulated in a data structure (see below).

Always name functions so that their names bear more than just a passing resembelance to their task, but avoid long function names. Function names should follow a naming convention where possible, in C this can be used as a primitive form of ``namespacing''.

Declare functions as static if they are not intended to be accessed by other parts of the system.

Functions should not be overlong. A good (understandable ) length for a function is around 40 to 80 lines. Any longer than this and it becomes difficult for other programmers to understand exactly what it does (simply limitations of human short term memory) any shorter than this and you may be needlessly introducing levels of indirection into program flow which is difficult to track.

Associated functions should be stored in the same C file. Hierachal splitting of functions is considered good programming style but it is useful for other programmers to be able to follow the flow of a program around the minimum number of files. Up to 10 associated function declarations within a single file is acceptable. An acceptable length for a C file is 250-500 lines, any longer than this and you should serously start considering common data flow and organisation to see if the routines would not be better split up. The main reason for having separate files is development flexibility. If two programmers need to simultaneously modify the same file then this will make integrating their efforts more complicated. You can thus make decisions on which functions to group together on the basis of considering which functions are likely to require joint modification.



Subsections
next up previous contents
Next: Data Structures Up: C Programming for Research. Previous: Indentation and Commenting   Contents
root 2017-09-20