Functions
Big Idea: User-defined functions are another great tool at our disposal.
Intuition: Let's rely on the fact that we've already been a *user* of functions and made function calls and made use of the values that are returned. What is new here is how we go about being the *author* of a function.
I also tend to think about a function as an "assistant" for which we can delegate a task. The assistant will do all the work, but we still need to think carefully about what instructions and information we send to the assistant, what work we expect the assistant to do, and how information might be conveyed back to us.
Let's focus on two distinct aspects of the new material.
1) Syntax/Semantics
- Syntax for declaring a function
- Paramater passing
- Return values
- Flow of control (and functions that call functions that call functions)
2) Advantage of functions in good software design
- Functions provide a way to consolidate code that is repeated in several places of a project (AVOID COPYING CHUNKS OF CODE)
- Functions (even if not needed to avoid duplication of code) can be a great tool in helping to organize code, as it allows us to take a complex task and to abstract the details so that those details are still given elsewhere, but not as a distraction in another part of code.
Common questions/confusions:
- calling a function vs defining a function
- parameter passing/naming
- what happens if the wrong number or types of parameters are sent to a function?
- use of return (vs print)
Examples:
- Let's write our own abs(x) function
- Let's revisit the two functions scale(data, factor) and scaledCopy(data, factor) from the end of the chapter
Michael Goldwasser
Last modified: Sunday, 22 December 2019