Chapter 7. All About Constants

The function of constants is a concept that is often taken for granted by most developers. On the surface, they seem simple and trivial. However, constants that are not used correctly can be a major source of development headaches.

Although most developers regard constants as a single concept, there are actually three categories of constants: substitution, bit field, and option. Each of these categories has different dynamics and different issues to deal with.

Substitution Constants

Substitution constants are the simplest type of constants. Basically, they are substituted for something else in code. See Example 7-1.

Example 7-1. Substitution constants
package oreilly.hcj.constants;
public class SubstitutionConstants {
  /** Holds the logging instance. */
  private static final Logger LOGGER = 
                Logger.getLogger(SubstitutionConstants.class);

  /** A value for PI. */
  public static final double PI = 3.141;

  public double getCircleArea(final double radius) {
    double area = (Math.pow(radius, 2) * PI);
    LOGGER.debug("The calculated area is " + area);
    return area;
  }

  public float calculateInterest(final float rate, 
                                 final float principal) {
    final String LOG_MSG1 = 
                                "Error: The interest rate cannot be less than ";
                   final String LOG_MSG2 = ". The rate input = ";
                   final double MIN_INTEREST = 0.0;

    // -- 
    if (rate < MIN_INTEREST) {
      LOGGER.error(LOG_MSG1 + MIN_INTEREST + LOG_MSG2 + rate);
      throw new IllegalArgumentException("rate");
    }
    return principal * rate;
  }
}

This code declares ...

Get Hardcore Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.