by s_tec · 11y ago · 0 comments
My default these days is to write numbers as numbers, plus maybe a comment if things are unclear. I only turn numbers and strings into named constants if they are used in more than one place, or if they are true configuration values that need to be tweaked.
This makes the program easier to read (the ultimate goal) by avoiding the need to jump around in the codebase. Comments are better at explaining things than cryptic variable names anyhow.
On the other hand, tools like CheckStyle can make people do some strange things when they take it too literally.
I once reviewed code that defined: static final int ONE_HUNDRED = 100;
Actually, the whole example smells ripe for refactoring. Where are there multiple windows throughout the app all sharing a default starting size? Sounds like it's time for a base class or something. Once you've eliminated the redundant sizing code, you will find that your default size values now exist in only one place (the base class). Since they are only in one place, you can write them as numbers again instead of named constants.
I've played this pattern out more times than I can count. The problem isn't magic values sprinkled through the code; it's having redundant code in the first place. Once you solve that, the magic numbers tend to evaporate.
static final int ONE_HUNDRED = 200; // Changed to 50 to optimizeAnd it's funny because it's true.
And ... the funny could have been eliminated if the named constant had just had a useful name, or been replaced by a function, rather than a passive-aggressive response to a code analyzer or coding standards ("There, I fixed it."). The conflict between the name and its value would have been eliminated, and the comment may have never been written in the first place.
I saw:
static final int ONE_HUNERD = 100;
a while back, which really made me laugh.
static final String HTTP = "http";
static final String COLON = ":";
static final String SLASH = "/";
String url = HTTP + COLON + SLASH + SLASH + ....;
Which I guess isn't wrong, but isn't right either :-)I'd pick
const DEFAULT_FONT_SIZE = 42;
// ... lots of code in the same file
var font = new Font(DEFAULT_FONT_SIZE)
over // 42 is the default font size
var font = new Font(42);
any time.Two reasons: version 2 encourages others to copy-paste out of laziness, and it does not resist refactoring very well.