Consider the constant in the following Java snippet :
public class ConsumerServiceTestFixture {
private ConsumerServiceTestFixture() {
throw new AssertionError("This class should not be instantiated");
}
public static final String CUSTOMER_ID_NOT_INTEGER = "12345678901";
}
The constant CUSTOMER_ID_NOT_INTEGER above is used to store a String which cannot be converted into an Integer because it's value is greater than Integer.MAX_VALUE.
This is not apparent from the name of the variable which conveys, at best, that the value is an 'invalid' customer_id. Nothing is conveyed about why the value is invalid.
One option would be to write a comment which says something like :
// Invalid since this number is greater than Integer.MAX_VALUE
public static final String CUSTOMER_ID_NOT_INTEGER = "12345678901";
However, if we had to write self-documenting code and not use comments, the only other option would be to make the variable name more descriptive. Something like :
public static final String CUSTOMER_ID_GREATER_THAN_INTEGER_MAX_VALUE = "12345678901";
But, with the above option I am not happy about the length of the variable name, specially if you consider the following snippet about optimal variable name length from Code Complete 2 :
How would you suggest I balance the length of the variable name vs. code readability ?
If instead of a // comment you use a /** comment (that is, javadoc), when a programmer uses your constant from an IDE or looks at your javadoc, he will get a full explanations of all the pros and cons of such a design, why it was done this way etc..
Unfortunately, you cannot name it "CUSTOMER_ID_THAT_IS_A_STRING_BECAUSE_IF_IT_WAS_AN_INT_IT_WOULD_BE_TOO_LARGE".