Sunday, August 23, 2009

Where do little functions come from?

It is rather easy to find potential functions from a carefully planned algorithm:
  • Any part of the algorithm that needs clarification is usually sensible to be implemented as a function
  • Any part of the algorithm that is repeated several times as such in the algorithm
With the help of these simple rules a programmer already gets far. Experience and practice give more perspective. It is good to remember what has been said about the length of functions: preferably no longer than what fits on the screen.

Functions with a return type are found the same way by reading the algorithm carefully. Additionally one must think what kind of information each function needs to give back to its caller (if any).

Often a function can be recognized as an action that is a part of a statement:

    IF discriminant == 0 THEN
    print the equivalent fahrenheit temperature to temperature in centigrade
    social security number <--- ask for the user's social security number

where potential functions are in italics.

A function can take two or more lines in the algorithm. Be careful!

prompt the user and ask for his/her social security number
read the user's input
WHILE the input is not a legal social security number
    print an error message
    prompt the user and ask for his/her social security number
    read the user's input
social security number <--- user's input

The actions in italics together form a function called askForSocialSecurityNumber()

Previous post

Next post

No comments:

Post a Comment