guides:programstyle:functions
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
guides:programstyle:functions [2020/08/04 15:32] – created wikiadmin | guides:programstyle:functions [2024/07/25 15:01] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 26: | Line 26: | ||
cin >> nickName; | cin >> nickName; | ||
cout << endl; | cout << endl; | ||
+ | </ | ||
+ | |||
+ | This code can be simplified through the use of a function: | ||
+ | <code c++> | ||
+ | string PromptForString(string prompt) { | ||
+ | | ||
+ | cout << "Enter your " << prompt << " => "; | ||
+ | cin >> tmp; | ||
+ | cout << endl; | ||
+ | | ||
+ | } | ||
+ | ... | ||
+ | |||
+ | // ask the user for a bunch of name related information | ||
+ | firstName = PromptForString(" | ||
+ | lastName = PromptForString(" | ||
+ | middleName = PromptForString(" | ||
+ | title = PromptForString(" | ||
+ | nickName = PromptForString(" | ||
</ | </ | ||
Line 31: | Line 50: | ||
===== Function Length ===== | ===== Function Length ===== | ||
+ | Functions should be viewable on a single screen. | ||
+ | |||
+ | 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 ===== | ===== Function Cohesion ===== | ||
- | ===== The main function | + | There are two aspects of function cohesion: |
+ | |||
+ | - The code in a function should perform a single well-defined task. | ||
+ | - 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 | ||
+ | |||
+ | ===== The main Function | ||
+ | |||
+ | The main function for most advanced programs should read like an algorithm to solve the main problem. | ||
+ | |||
+ | A single line main function is not acceptable. | ||
+ | ===== An Example ====== | ||
guides/programstyle/functions.1596555123.txt.gz · Last modified: 2024/07/25 15:01 (external edit)