12A. Mental Model of Functions 1:
What Does the Function Accomplish?


Contrasting what and how

You can think of a function in two ways.

It is important to distinguish the two. For example, let's return to the distance function.

  // distance(x1,y1,x2,y2) returns the distance between
  // points (x1,y1) and (x2,y2) in the plane.

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

Distance accomplishes what the comment says: distance(x1, y1, x2, y2) returns the distance between points (x1, y1) and (x2, y2) in the plane. Distance works by employing the distance formula that you learn about when you study algebra.


First ask, what is a function's job?

When you think about writing a function, the first question that you should ask is: What is this function supposed to accomplish? After you have answered that question precisely, think about how the function should work.


Make sure that a function does its job

Once you have finished writing a function definition, compare your answer to What should it accomplish? to your answer to how should it work?, as written in the function body. Does the function actually do what it is supposed to do?

Student programs frequently contain functions that do not do what they are supposed to do. Often, that is due to an error. But an astonishing fraction of the time, it is by design! In fact, it is clear that the student knows the function does not do its job, because another function compensates for that.


Fix what is broken

You will never get a complex program to work if its individual components do not do what they are supposed to do. That should be obvious. It is not enough for a function to do the right thing on some parameter values. It must do the exact right thing on all values of parameters that make sense. The standards for this course require that.

If a function does not accomplish exactly what it is supposed to accomplish, fix that function. Do not compensate for that mistake elsewhere.


Trust your functions

If you have defined a function correctly, then you should show some confidence in that. Do not try to work around some perceived mistake that is not even present. Look at the following code that uses distance.

  if(a == 0 && b == 0)
  {
    r = sqrt(c*c + d*d);
  }
  else 
  {
    r = distance(a,b,c,d);
  }
Clearly, the author of this code believes that distance(a, b, c, d ) does not work correctly when a and b are both 0, so he or she adds a special case to work around the perceived error in distance. In fact, distance(a, b, c, d ) works just fine when a and b are both 0. So the code above should be replaced by
  r = distance(a,b,c,d);