| Author |
Checkstyle - avoiding using 'magic numbers'
|
K DeLucia
Ranch Hand
Joined: Apr 11, 2008
Posts: 68
|
|
I'm pretty new to java and have just discovered CheckStyle. One of the messages I'm getting a lot of is # 'is a magic number'.
In one case I worked around it like this:
But what should I do in a case where I have a lot of numbers like this:
Is there some other way I should be doing this? Thanks for any input!
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
|
Well, in this particular case, it's much nicer to use column names rather than column numbers; this makes your code far more robust to database schema changes.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
K DeLucia wrote:But what should I do in a case where I have a lot of numbers like this:
If you still want to use the numbers, you can always use a counter:
Added bonus is that you can add a field in between without having to re-index. A downside is that the order is still important.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sridhar Santhanakrishnan
Ranch Hand
Joined: Mar 20, 2007
Posts: 317
|
|
What about cases where the numbers are not related?
I recently had to use iText to generate some Pdfs. There were so many numbers that I finally had to convince people to ignore those warnings.
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26192
|
|
I have my static analysis utility configured to ignore magic numbers above a certain threshold. (I think it is 10 or 15) to avoid the JDBC code being triggered. I don't like using the column names because if they change in the SQL, I have to remember to change them in the get/set methods. For the rare occasions where my JDBC code uses a ton of columns, I configure the static analysis tool to suppress the errors.
In your first example with the zip code, the tool is right. You do have a "magic number" in the code. You didn't work around it - you fixed a problem. It's traditional to use a real constant for this like:
private static final int ZIP_LENGTH = 11;
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26192
|
|
Sridhar Santhanakrishnan wrote:What about cases where the numbers are not related?
I recently had to use iText to generate some Pdfs. There were so many numbers that I finally had to convince people to ignore those warnings.
Why do yo have so many numbers in iText? I have mainly column widths in my iText code - which are all constants anyway. What other types of numbers do you have?
|
 |
 |
|
|
subject: Checkstyle - avoiding using 'magic numbers'
|
|
|