I wonder, in general, where the line should be drawn? Java coding
guidelines recommend that 1 and -1 can be used as literals, but other
integer constants should defined as a "constant" by the programmer.
What about zero?
Why should limit myself to just one line?
I draw a line between things that are unlikely to change and
those that may well change. Yes, I know that this is still blurry.
If I were writing code to do record blocking and deblocking, I
would not use literals in the work code for the physical and logical
record lengths.
If I were writing code dealing with weeks, I might well use 7 for
the number of days in a week.
I draw another line between simple (where I am much less likely
to bother) and complex (where I am much more likely to).
If the constants are local to just one procedure/method or a
short class, I might not bother. If the constants are used in more
than one place, I almost certainly will.
I draw a third line between temporary code and permanent code.
The former, unlikely; the latter, likely.
(Make sure that your "temporary" code really is temporary.)
I'm not sure that single character strings, or characters, should be
treated the same way. I can see cases for it, and I can see reasons for
not doing so, as Daniel implies.
It depends to me on what their use is. Run-of-the-garden use, as
in the code example you posted, hardly needs it.
Here's a grab from a recent discussion on transforming \u sequences in a
Java string. This is the bit in the Properties object that scans a line
read from a properties file for special escape sequences. I don't think
that the Java source APIs are the be-all and end-all of code style, but
it is a large public body of well-reviewed code. Note the abundant use
of single character constants, with out a programmer introduced
constant. It seems to read OK to me.
Likewise to me. It is short though so it does not prove much.
Were it a couple of pages long, it would be more of a test.
[snip]
Sincerely,
Gene Wirchenko