7E.2. Shortening Function Definitions

If you underutilize functions, you will find that the bodies of the functions that you write are very long. Long function definitions are difficult to understand and difficult to get to work.

The standards for this course require all function bodies to be no more than 16 noncomment lines long.

Put code that has a coherent purpose into a function definition, so that you don't need to clutter another function definition with details that are better put aside. A function whose body does two steps might look something like this.

  void doSomething(int x)
  {
    int y = firstStep(x);
    secondStep(y);
  }

Details of the two steps have been set aside into functions firstStep and secondStep. (But choose more descriptive names than firstStep and secondStep.)


Top-down design

Don't wait until the body of a function becomes unwieldy and then try to repair it. While you are writing a function definition, think about other functions that you would like to make use of. If they don't already exist, use them anyway. Do not put aside what you are working on to write those functions. Just ensure that you know what they are intended to do. You can come back to them later. That is called top-down design.