Chapter 2.2

The More Functions, the Better?

AmazonIn general, there are two categories of functions: those belonging to a class, or member functions, and those independent of everything, or nonmember functions. A function inside a class generally supplements that class by providing operations to manipulate its data members.

The main purpose of using a function is that when a module, usually main(), wants to do the same task more than once, it can simply call the function that performs the task whenever it needs to. Another purpose is to enhance readability of the program.

Therefore it is generally advisable to write functions that help main() or other functions do its work, rather than cram everything inside main() or the functions.My experience suggests that in general there should be no more than fifty lines in a function, a hundred tops. This way each function, accompanied by detailed comments, can be understood quickly. For example your main() needs to perform a complicated task that involves many operations. Then you can do something like this (pseudo code):

Now whoever maintaining your program can quickly understand what it’s trying to do just by looking at the function names. Inside each function it’ll also lay out its operations in a clear, organized way. If the function is small it doesn’t need to create other functions. If the function is big it’ll have to create other functions with meaningful names and delegate the tasks to them.

The most important rule of composing a function is to ensure its pre-conditions and post-conditions are fulfilled. They should be described in the comment section of the function. If you do a great job at it you may not even have to look any further while trying to understand what a function does or what parameters it accepts and rejects!

Whenever you want to write a function, carefully think about why and how often it’s needed. Are the arguments of the function general enough so that they can be used very often? Will the creation of this function enhance the readability and thus the maintainability of the program? Later on in Chapter 4 we will discuss the generality of a function, which is very important for a programmer to fully grasp when a function is necessary and how the function should be written!