0

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 :

Chapter 11. The Power of Variable Names

How would you suggest I balance the length of the variable name vs. code readability ?

3
  • 1
    Does the value of the constant really matter (larger than MAX_INT)? Why not simply INVALID_CUSTOMER_ID? Commented Jul 24, 2012 at 16:19
  • @assylias, the value of that constant is used in a test which tests the behavior of the related piece of code, when a String-which-is-an-invalid-integer is passed to it. Thus it must be greater than Integer.MAX_VALUE. Commented Jul 24, 2012 at 16:34
  • So why not "MAX_CUSTOMER_ID"? Bottom line: if you need more than two or three words, then you're not defining it clearly enough. IMHO... PS: I think "i" and "x1/x2" are ideal for many local variables. Never underestimate 1) the importance of 1) brevity, or 2) the usefulness of idiom Commented Aug 1, 2012 at 17:05

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.