Avoiding Mistakes

In this lesson, we will look at a specific example, and suggest ways to avoid coding errors.

We'll cover the following

Modules

When solving problems in previous chapters, we have written pseudocode to describe the steps in our solution. Each step often can be described by a sequence of even smaller steps, and these steps eventually will correspond to pieces, or modules, of our Java program. A module might be a class or, more likely, a method.

Example

We have seen that the definition of a method can consist of calls to several other, often private, methods. For example, the class Temperature in the previous chapter has the following public method convertToFahrenheit that calls two private methods:

/** Converts the temperature to Fahrenheit. */
public void convertToFahrenheit()
{
   switch (scale)
   {
      case C:
         convertCelsiusToFahrenheit();
         break;
      case K:
         convertKelvinToFahrenheit();
         break;
      default:
         assert scale.equals(Scale.F);
         break;
   } // End switch
} // End convertToFahrenheit

The intent of these steps is clear. Because we used an enumeration for the temperature scale, we know that scale can only be C, K, or F.

The definitions of the two private methods are each short. For example, let’s recall the following one from the previous chapter:

 // Converts a Kelvin temperature to Fahrenheit.
private void convertKelvinToFahrenheit()
{
    assert scale.equals(Scale.K) : "Unexpected scale: not Kelvin";
    convertKelvinToCelsius();
    convertCelsiusToFahrenheit();
} // End convertKelvinToFahrenheit

The conversion from Kelvin to Fahrenheit converts the Kelvin temperature to Celsius first and then to Fahrenheit. Rather than risking algebraic errors in converting directly from Kelvin to Fahrenheit, we call two private methods that each perform simple arithmetic.

Get hands-on with 1200+ tech skills courses.