Skip to main content

Section 12.1 Why Functions?

Beginner programmers often wonder why it’s worth the trouble to write other functions, when they could just do everything in main. The answer is that functions are a powerful tool for organizing and managing complexity.
We have already discussed some of the ways that functions manage complexity:
  • They enable abstractions. In a large codebase, developers can’t be expected to remember all the details of every corner of the code. A well designed function lets you use logic without having to know those details. You can think of a function as a black box that takes inputs, does something with them, and produces an output. You don’t need to know how it works; you just need to know what it does.
  • They enable efficient reuse of code. Rather than copy/pasting code from one part of a program (and then having to keep all of those copies in sync as you make changes), you can call the same function from many parts of a program.
In addition to those advantages, functions can be useful for the development process itself. Functions give us a powerful way to think about breaking a large problem into smaller, more manageable pieces, making it easier to focus on one manageable part of a problem at a time.
As we think about designing functions, we need to keep those reasons for using functions in mind. Good function design ensures that we have clean abstractions, efficient code reuse, and building blocks that can be developed independently.
You have attempted of activities on this page.