Some last notes on Functions
Objectives
We would like to :
- Understand function cohesion
Notes
- I amusing Dale chapter 4.
- A step is concrete if all implementation details are fully specified
- a line of an algorithm that corresponds to a few lines of code.
- A step is abstract if some of the implementation details are unspecified.
- A line of an algorithm that is probably best implemented as a function.
- A function is cohesive if
- All the parts do one thing and are related.
- All steps are either concrete or abstract but not both.
- Another definition is we can summarize the function in a good name.
- We would like to write cohesive functions.
- Dale suggests the following steps to writing cohesive functions
- Think about how you will solve the problem and write down steps.
- If a step is easy to implement in c++, it is concrete and you are done.
- If the step is abstract turn it into a function.
- A good abstract function should read like an algorithm.
- Let's take a look at My Homework 3 Design with this in mind.
- In general, function should be
- Cohesive
- Small, 1-30 lines
- Do not repeat code, build a sub function.
- That last statement is worth repeating
- Smaller functions are
- Easier to read and understand
- Therefore easier to debug
- And easier to test
- And easier to document
- And easier to modify
- Consider functions like M&Ms or potato chips, not like a candy bar or a sandwich.
- Should I write a single line function?
- There are times this might be appropriate, but rare
- Should I write a 100 line function?
- Unless it is a single simple task NO
- Should I have functions call functions
- If it is appropriate, yes.