Page 106 - Introduction to Programming with Java: A Problem Solving Approach
P. 106
72 Chapter 3 Java Basics
The above code fragment is somewhat confusing. The meaning behind the hard-coded constant 299792458.0 may be clear to science techies, but it isn’t very clear to the rest of us. For a better solution, use a named constant.
Named Constants
A named constant is a constant that has a name associated with it. For example, in this code fragment, SPEED_OF_LIGHT isanamedconstant:
final double SPEED_OF_LIGHT = 299792458.0; // in meters/sec
.. .
propagationDelay = distance / SPEED_OF_LIGHT;
As you should be able to discern from this code fragment, a named constant is really a variable. Now there’s an oxymoron—a constant is a variable. Note how SPEED_OF_LIGHT is declared to be a double variable, and it’s initialized to the value 299792458.0. How is the SPEED_OF_LIGHT initialization different from initializations that you’ve seen in the past? The word final appears at the left.
The reserved word final is a modifier—it modifies SPEED_OF_LIGHT so that its value is fixed or “final.” And being fixed is the whole point of a named constant. Thus, all named constants use the final modifier. The final modifier tells the compiler to generate an error if your program ever tries to change the final variable’s value at a later time.
Standard coding conventions suggest that you capitalize all characters in a named constant and use an underscore to separate the words in a multiple-word named constant. Example: SPEED_OF_LIGHT. The
Apago PDF Enhancer
rationale for the uppercase is that uppercase makes things stand out. And you want named constants to stand out because they represent special values.
Named Constants Versus Hard-Coded Constants
Not all constants should be named constants. For example, if you need to initialize a count variable to 0, use a hard-coded 0 like this:
int count = 0;
So how do you know when to use a hard-coded constant versus a named constant? Use a named constant if it makes the code easier to understand. The above count initialization is clear the way it is now. If you re- placethe0withanamedconstant(e.g.,int count = COUNT_STARTING_VALUE),itdoesnotimprove the clarity, so stick with the hard-coded constant. On the other hand, this code is unclear:
propagationDelay = distance / 299792458.0;
By replacing 299792458.0 with a SPEED_OF_LIGHT named constant, it does improve the clarity, so switch to the named constant.
There are two main benefits of using named constants:
1. Named constants make code more self-documenting, and therefore more understandable.
2. If a programmer ever needs to change a named constant’s value, the change is easy—find the named constant initialization at the top of the method and change the initialization value. That im-
Make it easy plements the change automatically everywhere within the program. There is no danger of
to change.
forgetting to change one of many occurrences of some constant value. There is consistency.