7E.1. Avoiding Code Duplication

Functions are critical for breaking a large program up into manageable pieces. But there are some other reasons for writing functions.

The more code you write, the more opportunities you have for making mistakes. The more opportunities you have, the more mistakes you will make. Clearly, you want to avoid writing the same code more than once.

But what if you have two bits of code that are similar but not identical? For example, in one place you need

  d = sqrt(pow(x1-x2, 2) + pow(y1-y2, 2));
but in another place you need
  r = sqrt(pow(a-c, 2) + pow(b-d, 2));
You can avoid that duplication by creating a function.
  // distance(x1,y1,x2,y2) returns the distance between
  // points (x1,y1) and (x2,y2) in the plane.

  double distance(double x1, double y1, double x2, double y2)
  {
    return sqrt(pow(x1-x2, 2) + pow(y1-y2, 2));
  }
then replace the two statements above by
  d = distance(x1,x2,y1,y2);
and
  r = distance(a,b,c,d);
Not only does that avoid duplicating code, but it makes what you are doing more clear. It also allows you to make improvements that would be awkward when the code is duplicated. It is much more efficient to compute z*z than to compute pow(z,2). So you write function distance as follows.
  // distance(x1,y1,x2,y2) returns the distance between
  // points (x1,y1) and (x2,y2) in the plane.

  double distance(double x1, double y1, double x2, double y2)
  {
    double deltaX = x1 - x2;
    double deltaY = y1 - y2;
    return sqrt(deltaX*deltax + deltaY*deltaY);
  }


Code duplication standard

I expect you not to duplicate code unnecessarily, and you will lose points for duplicating code. But don't overdo it. If an expression or statement is short and simple, just write it. For example,

  n++;
can occur in several places. Don't try to make a function that adds 1 to a variable. Use a function when it makes the body of another function shorter, simpler or more readable.