Prefix variable antipattern
// NO!
public static final String DR_PREFIX = "Dr. ";
// ---
System.out.println("Hi, %s!", DR_PREFIX + "Nick Riviera");
It’s obviously incorrect to write name + DR_PREFIX, and yet defining a constant does nothing to prevent this.
Use a helper method instead of string constants intended to be prefixes/suffixes.
// Yes!
public static String doctor(name) {
return "Dr. " + name;
}
// ---
System.out.println("Hi, %s!", doctor("Nick Riviera"));
Prefix/suffix variables couple all of their callers to a particular pattern of use (prefixVar + yourVar, yourVar + suffixVar, etc.). If that pattern has to change, your callers have to change.
// Oof.
public static final String DR_SUFFIX = ", M.D."; // IDE-assisted renaming to reflect the constant's new placement.
// ---
System.out.println("Hi, %s!", "Nick Riviera" + DR_SUFFIX); // Did you review every renamed use? Are you sure?
If you instead define a helper method, you encode the placement next to the customization to insulate the rest of the code from this detail. If your format needs to change, you change the helper and leave the call sites alone.
// Yes!
public static String doctor(name) {
return name + ", M.D.";
}
// ---
System.out.println("Hi, %s!", doctor("Nick Riviera")); // No change needed!