User Tools

Site Tools


guides:programstyle:functions

This is an old revision of the document!


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

Function Cohesion

The main function

guides/programstyle/functions.1596555161.txt.gz · Last modified: 2024/07/25 15:01 (external edit)