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*
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 double getCircleArea(final double radius) { double area = (Math.pow(radius, 2) *`public static final double PI = 3.141;`

); LOGGER.debug("The calculated area is " + area); return area; } public float calculateInterest(final float rate, final float principal) {`PI`

`final String LOG_MSG1 =`

`"Error: The interest rate cannot be less than ";`

`final String LOG_MSG2 = ". The rate input = ";`

// -- if (rate < MIN_INTEREST) { LOGGER.error(`final double MIN_INTEREST = 0.0;`

+ rate); throw new IllegalArgumentException("rate"); } return principal * rate; } }`LOG_MSG1 + MIN_INTEREST + LOG_MSG2`

This code declares ...

Start Free Trial

No credit card required