Radford University ITEC

ITEC120

lect01:
A First Program

Consider Krusteaze Pizza, where you ask a server:

So in a calculator, you can type in expressions — that's a simple program! Well yes, exceedingly simple — it's a program which computes the area of a 16" pizza. Programs don't become interesting until we generalize them to be able to handle different inputs. In this case, it would be convenient to just type in the diameter, and have the computer calculate the rest. In fact, in high school algebra, you did this:

A(d) = pi * (d/2)^2
This is a general case, which abstracts d=12, d=14, d=18, and any other diameter13.

How to translate this algebra into Java?
Attempt 1 (of quite a few):

  pieArea(d) {
    return 3.14 * (d/2) * (d/2);
    }
To call this Java function, we'll write (in a moment) something like:
pieArea(12) (this evaluates to ...)
pieArea(14) (this evaluates to ...)

This definition is close, but not quite complete Java yet. It does abstract the repeated calculation into a function, which makes us happy. "d" is called the function's "formal parameter", and when we call the function we pass the function a concrete "argument" (e.g. 12 or 14 or 18).

This Java definitioon of pieArea is similar to the way it's specified in the arithmetic, but with some extra scaffolding: curly-brackets around the body of the function, the keyword return, and a semicolon at the end of the return statement. They are simply things Java requires you to add, to write the function.

While some programming languages might accept the above, Java requires you to specify a bit more information: it needs you do specify the type of the argument given to the function, as well as the type which gets returned by the function. In this case, the type is "Number", or more specifically, double (for `double-precision estimates'; we can tell it's an estimate14 because clearly 3.14 is not the correct value of π).

Other types are integers (int), true/false (boolean), or more sophisticated types like Set or Dictionary or MouseEvent — We'll get into all that over the course of the class!

Okay, back to our program; this is how we specify that the argument d is a double, and that the function returns a double: Attempt 2:

  double pieArea( double d ) {
    return 3.14 * (d/2) * (d/2);
    }
This is a plausible Java, and it actually runs. Let's try it: From BlueJ, find the main window: Congratulations, you have written your program, gotten it running, and even run a couple of cursory test cases!

Alas, just getting a function to run isn't enough. Why not? Well, consider coming across the following code (which does run):

  double f( double r ) {
    return 3.14 * r * r * r / 3;
    }
Is this a good function? Is the formula it computes correct? We have no idea! If trying to compute the volume of a right-cone with radius r, then it's correct; if trying to compute the surface area of the cone then it's wrong, and if it's calculating something else entirely, it may or may not be correct.
The Zeroth Law of Programming
Code is meant to be read by humans.
At the least, this law requires that each function must have a clear description of what it computes. Even if a computer might be able to do something with undocumented code, it's useless to people (including the person who wrote it, after a week, when they don't remember exactly what each function does.)

(One very easy mistake to make with functions we've written, is remembering that pieArea should be passed the pizza's diameter, not the radius. There is no way for the computer to help us remember this.)

We'll come back later to what comprises an adequate description. Note that just the fact of choosing a good “self-documenting” name goes a long way; avoid generic names like f or calculate or doIt. But, just because a name seems self-documenting to you doesn't necessarily mean that further comments aren't needed. For example,

     double rightConeSurfaceArea( double r )
This name is fairly descriptive about what the function returns. But other programmers who use this function might still have questions: Does this function include the cone's base, in the surface area? Does it include the inside and outside of the cone (which is important if painting an actual cone inside and out).

Okay, back to our pieArea example, Attempt 3, where we add a description. Descriptions precede the function, and are enclosed by /* and */:

  /** pieArea
   *  Given a nonnegative diameter d (in inches), return the surface
   *  area of the pizza top (in square inches).
   *  Accurate to within 1%.
   */
  double pieArea( double d ) {
    return 3.14 * (d/2) * (d/2);
    }
This is the first acceptable version, (though as we'll see later, there are a couple of improvements yet in store).

A second function

Some customers are concerned with the surface area of their pizza. Others prefer crusts, and want to ask the server how much blank crust each pizza comes with. The server happens to know that Krusteaz Pizzas have a 2″ border of crust around them (what cheapskates!). Let's write the function crustArea:

Magic Numbers

What if the value or Pi changes? Well, more particularly, we knnow that 3.14 is a poor approximation, and we want to use the more accurate 3.14159.
What's wrong with doing a search-replace of '3.14' with '3.14159'?
Solution: Create a named constant, and attach it to the value 3.14; then use that name instead of the literal digits "3.14", in the rest of your program. You might have
       final double PI = 3.14159;                     /* The math constant. */
       final double ARTICHOKE_COST_PER_POUND = 3.14;  /* Cost in dollars. */
These lines tell Java "create the name ARTICHOKE_COST_PER_POUND, and associate it with the value 3.14 forevermore (well, until the program ends)". Like functions, you need to attach the type (here, "double"); the keyword "final" assures this value won't change.
The Third Law of Programming
No magic numbers.
As a matter, of fact, π is such a common constant, that it already comes pre-defined in Java: somewhere inside the Java libraries is a line
     final double Math.PI = 3.14159265358979;
By convention, all-caps are used when naming constants. (The prefix “Math.” is actually a package name—we'll discuss packages much later—so you don't think that a period ‘.’ is allowed as part of ordinary Java names.) Underscores are allowed in names, as in ARTICHOKE_COST_PER_POUND. (Spaces cannot be used—it would look like different words! Hyphens, even though used in English for compound words, cannot be used (at least in Java), since it would think you are subtracting two different constants.) (This guidelines are true for names of functions, as well as names of constants.)
Let's revisit pieArea:
  /** pieArea
   *  Given a nonnegative diameter d (in inches), return the surface
   *  area of the pizza top (in square inches).
   *  Accurate to within 1%.
   */
  double pieArea( double d ) {
    return 3.14 * (d/2) * (d/2);
    }

Readability tip: When writing comments, start them with a capital letter and finish with a period. (You don't need full sentences though; fragments are sometimes fine.) See the above examples.
Why? We've been trained from age 5 to read with these conventions; leverage this to make it that much easier on people reading your code (which includes people grading your code!)
RE-CAP: Syntax.

Frequently, you'll find yourself defining a second constant who is based on a first — e.g.

         final int HEIGHT = 200;           /* In pixels. */
         final int WIDTH  = HEIGHT * 2;    /* In pixels. */
Use this if you want the width to vary proportional to the height. If you want to fix the width as 400, regardless of somebody later tweaking the height, you'd assign it to 400 directly


13well, non-negative diameter      back

14Single-precision estimates are archaic and we won't use them; they are called `float'.      back

15 Note that sometimes, code-reuse is easier said than done; if you'd named your function 'discArea' instead of 'pieArea', then the manager's shape-change would require finding all places where 'discArea' was called, and decide whether it was being used for pizza-area purposes, or for other purposes.      back


Ian's home page Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu Last modified 2006.Aug.31 (Thu)