User Tools

Site Tools


guides:programstyle:functions

Functions

The proper use of functions can create code which is readable, can be debugged, and can be extended. Functions can break code into small, more understandable segments. Functions can be used to eliminate duplicated code.

The local style guide suggests students err on the side of creating too many functions.

Repeated Code

Programmers should use functions in place of repeated code. If a block of code is used repeatedly in a program, eliminate it by writing a function to perform the associated task.

The following code has the same code segment repeated many times:

   cout << "Enter your First Name =>";
   cin >> firstName;
   cout << endl;
   cout << "Enter your Last Name =>";
   cin >> lastName;
   cout << endl;
   cout << "Enter your Middle Name =>";
   cin >> middleName;
   cout << endl;
   cout << "Enter your Title =>";
   cin >> titleName;
   cout << endl;
   cout << "Enter your Nickname =>";
   cin >> nickName;
   cout << endl;

This code can be simplified through the use of a function:

string PromptForString(string prompt) {
   string tmp;
   cout << "Enter your " << prompt << " => ";
   cin >> tmp;
   cout << endl;
   return tmp;
}
...
 
// ask the user for a bunch of name related information
firstName = PromptForString("First Name");
lastName = PromptForString("Last Name");
middleName = PromptForString("Middle Name");
title = PromptForString("Title");
nickName = PromptForString("Nickname")

Function Length

Functions should be viewable on a single screen. The programmer should be able to read all, or nearly all of a function at the same time.

A standard ascii terminal is 24 lines high, so this is a reasonable goal for function length.

Functions should rarely exceed 50 lines.

Function Cohesion

There are two aspects of function cohesion:

  1. The code in a function should perform a single well-defined task.
  2. The code in a function should be at the same level of abstraction.

In the first case, this may be a simple or very complex task but it is a single task.

In the second case, the program should consist of either high level (other function calls) or low level (computation, input, …) actions. High level routines should read like an algorithm.

The main Function

The main function for most advanced programs should read like an algorithm to solve the main problem. It should not contain detailed code, but consist of a number of calls to functions.

A single line main function is not acceptable.

An Example

guides/programstyle/functions.txt · Last modified: 2022/08/02 11:59 by 127.0.0.1