• (cs)
    many developers agree that it's best to define a constant named "FOUR"

    ...are you mad? If many developers agree on this, I am going to have to become an artist.

    A constant exists so it can be used in many places but defined and changed in just one. What are you going to change FOUR to? 5?

    Constants are there to keep code DRY, not to give cute (wrong) names to things.

  • pallen (unregistered) in reply to LennyPain
    LennyPain:
    Paula:
    UPPERCASE_T_STRING + LOWERCASE_H_STRING + LOWERCASE_A_STRING + LOWERCASE_T_STRING + ONE_SPACE_STRING + LOWERCASE_I_STRING + LOWERCASE_S_STRING + ONE_SPACE_STRING + LOWERCASE_B_STRING + LOWERCASE_R_STRING + LOWERCASE_I_STRING + LOWERCASE_L_STRING + LOWERCASE_L_STRING + LOWERCASE_A_STRING + LOWERCASE_N_STRING + LOWERCASE_T_STRING + EXCLAMATION_MARK_STRING

    "That is brillant!" ??? Error: Won't compile!

    Forgot NULL_TERMINATION_CHARACTER.

  • Ben (unregistered) in reply to thenextguy
    thenextguy:
    Auch, that hurts!

    I use magic numbers all the time, I just make sure there's a comment line next to it explaining them. e.g. malloc(17) // 4*4(int) + 1 (\0)

    why not malloc(num_items * sizeof(data_struct))? Or, better, just use calloc(...) It's going to be a constant when it compiles anyway, and it's more or less self-commenting.

    The only place I find I need magic numbers is in my header files that describe binary structures.

  • Kyle Z. (unregistered)

    it's only a problem of nomenclature! public static final int MAYBE_FOUR = 5; OR public static final int MY_FOUR = 5; AND we're ready to go!

    captcha: similis. Almost an ugly disease.

  • fahadsadah (unregistered)

    This is not a WTF.

    On embedded systems with no filesystem...

  • The Nerve (unregistered)

    I think that most people already get this, but if they did, then this wouldn't keep cropping up so often.

    Ok:

    x = x1 + vt - 4.9 * t * t;

    Slower, but more readable:

    x = x1 + vt + .5 * -9.8 * t * t;

    In case I forgot what 9.8 is or can't figure it out based on context:

    x = x1 + vt + .5 * Constants.ACCELERATION_OF_GRAVITY * t * t;

    or

    x = x1 + vt + Constants.ONE_HALF_OF_GRAVITY * t * t;

    Completely stupid:

    x = x1 + vt + Constants.POINT_5_TIMES_NINE_POINT_EIGHT * t * t;
  • Lord0 (unregistered) in reply to frits

    I can hear Jimi!

  • Kempeth (unregistered) in reply to powerlord
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

  • Anonymous (unregistered) in reply to lesliev
    lesliev:
    many developers agree that it's best to define a constant named "FOUR"
    ...are you mad? If many developers agree on this, I am going to have to become an artist.

    A constant exists so it can be used in many places but defined and changed in just one. What are you going to change FOUR to? 5?

    Constants are there to keep code DRY, not to give cute (wrong) names to things.

    When you've calmed down you might want to read this. Does it make sense now?
  • Anonymous (unregistered) in reply to Kempeth
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

  • kikito (unregistered)

    This gave me killer instincts.

    Also, the captcha word for this comment was "genitus".

  • wtf (unregistered) in reply to Anonymous
    Anonymous:
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

    When you've calmed down you might want to read this. Does it make sense now?

  • Bob (unregistered) in reply to MatDey
    MatDey:
    public static final String ONE_STRING = "9";

    lolz

    Note the (somewhat misplaced) ellipsis. The original code included:

    public static final String ONE_STRING = "9";
    public static final String ANOTHER_STRING = "3";
    public static final String YET_ANOTHER_STRING = "9.8";
    
  • JRR++ (unregistered)

    ONE_STRING to rule them all, ONE_STRING to find them ONE_STRING to bring them all and in the compiler bind them

  • Ken B. (unregistered)
    select final_int as INTEGER_THREE
    from NoMoreMagic
    where name = 'INTEGER_THREE';
    
    select final_int as INTEGER_FOUR
    from NoMoreMagic
    where name = 'INTEGER_FOUR';
  • n_slash_a (unregistered) in reply to Pretty Mad Developer
    Pretty Mad Developer:
    This kind of code often comes from having the "magic constant" rule enabled in PMD, and a "zero PMD warning" policy. This proves, if anything, that blindly applied rules are almost always stupid.

    TRWTF is, what do you do if Oracle suddenly decides to change Java keywords? That's where C got it right with preprocessor directives:

    #define IF_KEYWORD if

    (captcha: "odio" -> "hatred" in spanish)

    FTW!

    Oh wait.... sorry

    #define FOR_THE_WIN_EXCLAMATIONPOINT_ABBREVIATION_STRING "For The Win!"

  • Bill&Ted (unregistered) in reply to lesliev
    lesliev:
    many developers agree that it's best to define a constant named "FOUR"

    ...

    A constant exists so it can be used in many places but defined and changed in just one. What are you going to change FOUR to? 5?

    ...

    Not necessarily changed - the value of Math.PI [1] is never going to change, but it's still sensible to make it a constant so that (1) developers don't have to remember the value; and (2) they can't screw up by making a typo (OK, other than making it Math.PHI or something..).

    [1] unless someone got it wrong originally...

  • (cs) in reply to Andreas
    Andreas:
    Magic numbers are way overrated (I guess because it is so easy to check if someone uses them). You should use your brain instead of converting everything into a constant.

    Exactly.

    You should use a constant definition, instead of the literal constant, if:

    • the value isn't easily understood at first glance (e.g. instead of 0.3048, define CONVERT_FEET_TO_METERS)
    • the value could change in the future, e.g. array size, pixel dimensions of a widget, maximum size of a defined data structure
    • giving the constant a descriptive name will help you understand what the code is doing (e.g. defining "4" as FOUR is totally, utterly, useless!)

    Otherwise, just use the constant, and if necessary, document what you're doing with a comment.

    To use the example from the story, you wouldn't want to define a constant FOUR just so you could divide a value into quarters. If, however, you expect that the number of slices might one day change, then you define

    #define NUMBER_OF_SLICES 4

    x = y / NUMBER_OF_SLICES;

    This is surely not news to any programmer, but it's surprising how many people just don't seem to get it.

  • Ken B. (unregistered) in reply to Bill&Ted
    Bill&Ted:
    Not necessarily changed - the value of Math.PI [1] is never going to change, but it's still sensible to make it a constant so that (1) developers don't have to remember the value; and (2) they can't screw up by making a typo (OK, other than making it Math.PHI or something..).

    [1] unless someone got it wrong originally...

    Well, the value of Math.PI might change. Consider moving to a platform more a different floating-point precision. (Or does Java require a certain precision, regardless of platform?)

    Or, maybe you're running your program in Indiana.

  • J. Madden (unregistered) in reply to Matt Westwood
    Matt Westwood:
    SDR:
    I have been quietly reading, enjoying, and sharing the wft for years. Today I am oddly compelled to comment. This one is literally melting my brain.

    OMFGWTF

    I sincerely hope your use of "literally" is literally incorrect.

    Seems fine to me.

  • Nik (unregistered) in reply to Matt Westwood

    hahahaha, pwnd

  • Nik (unregistered) in reply to Matt Westwood
    Matt Westwood:
    SDR:
    I have been quietly reading, enjoying, and sharing the wft for years. Today I am oddly compelled to comment. This one is literally melting my brain.

    OMFGWTF

    I sincerely hope your use of "literally" is literally incorrect.

    hahahaha, pwnd

    (whoops on the previous post)

  • CoderDan (unregistered)

    Perhaps you have forgotten the most important constant.... INEGER for when an integer just won't do.

    Captcha: Validus -- Lesser known brother of Spartacus.

  • Nik (unregistered) in reply to J. Madden
    J. Madden:
    Matt Westwood:
    I sincerely hope your use of "literally" is literally incorrect.

    Seems fine to me.

    nice, I can't tell if you're joking

  • (cs)

    Bah. I occasionally (rarely) use magic numbers in some of my code. For example, we have some numbered data sources (data suppliers), and while their numbers can't change, their names sometimes do, so translating from a name to a number using a table won't work.

    If data source 17 is so-and-so, I'll put a 17 in the code, and comment who that supplier is.

    And why are the negative numbers big integers?

  • thenextguy (unregistered) in reply to Steve The Cynic
    Steve The Cynic:
    thenextguy:
    Auch, that hurts!

    I use magic numbers all the time, I just make sure there's a comment line next to it explaining them. e.g. malloc(17) // 44(int) + 1 (\0)

    Tsk. The 44(int) is presumably to indicate that you want 4 lots of 4-byte ints, right? But ints aren't 4 bytes (well, not necessarily, anyway: I once worked on a system where it would have been reasonable for CHAR_BITS == INT_BITS == 16, and plenty of systems a bit later with sizeof(int) == 2). Also, this is just duplicating the magicness in the comments: what is the first 4? And why not this?

    malloc( 4*sizeof(int)+1 ); // one int per season of year, 1 byte for trailer

    Now the comment explains what the magic number means.

    I was replying a bit hasty. Didn't want to type that much :)

  • thenextguy (unregistered) in reply to thenextguy

    If I used to much comment, my comment quota for the day would run out and I'll have no more left for my actual code :(

  • Anonymous (unregistered) in reply to wtf
    wtf:
    Anonymous:
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

    When you've calmed down you might want to read this. Does it make sense now?

    No, not at all. If you're trying to say that the OP was joking I suggest you point out exactly what part appears humorous. It was either a troll or a serious suggestion, but it sure as hell wasn't humor. Not that I'd expect you to understand wtf, you've always had a major problem with humor, in terms of both identification and delivery.

  • Melvis (unregistered) in reply to Paula
    Paula:
    UPPERCASE_T_STRING + LOWERCASE_H_STRING + LOWERCASE_A_STRING + LOWERCASE_T_STRING + ONE_SPACE_STRING + LOWERCASE_I_STRING + LOWERCASE_S_STRING + ONE_SPACE_STRING + LOWERCASE_B_STRING + LOWERCASE_R_STRING + LOWERCASE_I_STRING + LOWERCASE_L_STRING + LOWERCASE_L_STRING + LOWERCASE_A_STRING + LOWERCASE_N_STRING + LOWERCASE_T_STRING + EXCLAMATION_MARK_STRING

    I can't believe I looked at this long enough to realize that you spelled "brilliant" wrong. Nice...

  • ThomasP (unregistered) in reply to COMMENT_FRIST
    COMMENT_FRIST:
    COMMENT_FRIST = 3;

    Fixed.

  • Larry (unregistered) in reply to Anonymous
    Anonymous:
    wtf:
    Anonymous:
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

    When you've calmed down you might want to read this. Does it make sense now?

    No, not at all. If you're trying to say that the OP was joking I suggest you point out exactly what part appears humorous. It was either a troll or a serious suggestion, but it sure as hell wasn't humor. Not that I'd expect you to understand wtf, you've always had a major problem with humor, in terms of both identification and delivery.

    TRWTF is that Java has no datatype for an infinite-precision number.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    Someone You Know:
    Allen's colleague:
    public static final int COMPARE_RESULT_ZERO = 0 ; public static final int COMPARE_RESULT_ONE = 1 ; public static final int COMPARE_RESULT_NEGATIVE = -1 ;

    It seems likely these are being used somewhere in conjunction with a Comparable or Comparator. If that's the case there's another WTF here in assuming that compareTo() methods will return -1 for "less than" and +1 for "greater than". The only assumption you're allowed to make is that it returns a negative value for "less than" and a positive value for "greater than".

    Oh wake up. You just check the return value as greater-than-or-equal to the ONE value and less-than-or-equal-to the "NEGATIVE" value. Cor I dunno, do I have to do ALL your design for you.

    What happens when compareTo() returns an int between 0 and -1? It's important to consider edge cases like this.

  • wtf (unregistered) in reply to Anonymous
    Anonymous:
    wtf:
    Anonymous:
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

    When you've calmed down you might want to read this. Does it make sense now?

    No, not at all. If you're trying to say that the OP was joking I suggest you point out exactly what part appears humorous. It was either a troll or a serious suggestion, but it sure as hell wasn't humor. Not that I'd expect you to understand wtf, you've always had a major problem with humor, in terms of both identification and delivery.

    You're mean. Schniffle.

    (not to mention dumb as a bag of rocks, if you really think you're the only person reading this who understands the limitations of floating point precision or the impossibility of a precise representation of pi)

  • by (unregistered) in reply to wtf
    wtf:
    Anonymous:
    wtf:
    Anonymous:
    Kempeth:
    powerlord:
    Note to spoil your joke or anything... but Java already has a double not quite pi constant: java.lang.Math.PI

    Really? I always thought that those constants where EXACTLY equal to pi...

    This must be a troll. Even the lowest level of junior should understand why a double can never be exactly equal to pi, so either this is a troll or you're actually a toddler. Oh well, let me give you a hint anyway: precision.

    When you've calmed down you might want to read this. Does it make sense now?

    No, not at all. If you're trying to say that the OP was joking I suggest you point out exactly what part appears humorous. It was either a troll or a serious suggestion, but it sure as hell wasn't humor. Not that I'd expect you to understand wtf, you've always had a major problem with humor, in terms of both identification and delivery.

    You're mean. Schniffle.

    (not to mention dumb as a bag of rocks, if you really think you're the only person reading this who understands the limitations of floating point precision or the impossibility of a precise representation of pi)

    Actually, I think the troll is on the other foot.

  • Sydney (unregistered) in reply to Lord0
    Lord0:
    I can hear Jimi!

    Look man, you can listen to Jimi but you can't hear him.

  • (cs) in reply to Melvis
    Melvis:
    Paula:
    UPPERCASE_T_STRING + LOWERCASE_H_STRING + LOWERCASE_A_STRING + LOWERCASE_T_STRING + ONE_SPACE_STRING + LOWERCASE_I_STRING + LOWERCASE_S_STRING + ONE_SPACE_STRING + LOWERCASE_B_STRING + LOWERCASE_R_STRING + LOWERCASE_I_STRING + LOWERCASE_L_STRING + LOWERCASE_L_STRING + LOWERCASE_A_STRING + LOWERCASE_N_STRING + LOWERCASE_T_STRING + EXCLAMATION_MARK_STRING

    I can't believe I looked at this long enough to realize that you spelled "brilliant" wrong. Nice...

    I think you meant to say that he spelled "brillant" correctly.

    As an aside, it was actually pretty smart to do this sort of thing in Ye Olde 8-bit Atari BASIC. Numeric literals consumed six bytes in the code, but variable references only took two bytes, so you could save a lot of space in large programs by converting all commonly-used numbers to variables.

    100 N1=1:N2=N1+N1:N3=N2+N1:N4=N3+N1:N5=N4+N1

    Ahhh, memories...

  • Larry (unregistered) in reply to Someone You Know
    Someone You Know:
    Matt Westwood:
    Someone You Know:
    Allen's colleague:
    public static final int COMPARE_RESULT_ZERO = 0 ; public static final int COMPARE_RESULT_ONE = 1 ; public static final int COMPARE_RESULT_NEGATIVE = -1 ;

    It seems likely these are being used somewhere in conjunction with a Comparable or Comparator. If that's the case there's another WTF here in assuming that compareTo() methods will return -1 for "less than" and +1 for "greater than". The only assumption you're allowed to make is that it returns a negative value for "less than" and a positive value for "greater than".

    Oh wake up. You just check the return value as greater-than-or-equal to the ONE value and less-than-or-equal-to the "NEGATIVE" value. Cor I dunno, do I have to do ALL your design for you.

    What happens when compareTo() returns an int between 0 and -1? It's important to consider edge cases like this.

    TRWTF is that Java is around 15 years old, and you still are not able to define non-Integer ints.

  • (cs) in reply to NoAstronomer
    NoAstronomer:
    If only more languages had the ability to change constants on the fly. It's the way of the future.
    No, it's the way of the past. Fortran had this ability forty years ago:
        SUBROUTINE FRED(A,B)
        A = B
        END
    ...
        CALL FRED(7,4)
        WRITE(5,*) 7

    output of this program on machines that support this:

    4

    WTF?!?

    (On other machines, e.g. Sun's Solaris Fortran, it crashes when writing to A in FRED() because the 7 is stored in a read-only section. It is still passed by reference, though.)

  • (cs) in reply to Larry
    Larry:
    TRWTF is that Java is around 15 years old, and you still are not able to define non-Integer ints.
    Non-integer integers? That's easy... those are implemented by the Schrodinger class.
  • Mr. Bob (unregistered)

    My eyes are burning. Is that the magic happening?

  • Veggie (unregistered)
    public static final Long LONG_VALUE_ZEARO = Long.valueOf(0);
    ...
    public static final String ONE_STRING = "9";
    

    Haha, these could get bad.

  • Nome de Plume (unregistered) in reply to thenextguy
    thenextguy:
    Auch, that hurts!

    I use magic numbers all the time, I just make sure there's a comment line next to it explaining them. e.g. malloc(17) // 4*4(int) + 1 (\0)

    I still love using the sizeof operator. Someday, your 64-bit integer program might move to a 128-bit machine.

    int arr = malloc(4sizeof(int));

    I have no idea why you put a NULL terminator on a non-string array.

  • qbolec (unregistered)

    I actually wrote something like that, it was:

    const int NUMBER_OF_FINGERS = 10;

    This was my response to the request to remove all magic constants from the code, part of which converted numbers from binary to base 10. The QA guy insited to change all nubmers to some meaningfull constants, decribing the reason and purpose of their use. After a moment of reflection I realized that was the only possible name for the constant.

    Others included:

    const int BEGIN_OF_THE_ARRAY = 0;

    and

    const int NUMBER_YOU_HAVE_TO_SUBTRACT_FROM_SIZE_OF_ARRAY_TO_GET_LAST_ELEMENT = 1;

  • Bob (unregistered) in reply to Zylon
    Zylon:
    Non-integer integers? That's easy... those are implemented by the Schrodinger class.

    Weirdly, the superposition of two integers is still an integer.

  • (cs) in reply to Mr. Bob
    Mr. Bob:
    My eyes are burning. Is that the magic happening?

    Black Magic. Or maybe Chemical Warfare.

  • Ole The Swedish Sawmill Operator (unregistered) in reply to qbolec
    qbolec:
    I actually wrote something like that, it was:

    const int NUMBER_OF_FINGERS = 8;

    FTFY

  • Nome de Plume (unregistered) in reply to bertram
    bertram:
    Steve The Cynic:
    thenextguy:
    Auch, that hurts!

    I use magic numbers all the time, I just make sure there's a comment line next to it explaining them. e.g. malloc(17) // 44(int) + 1 (\0)

    Tsk. The 44(int) is presumably to indicate that you want 4 lots of 4-byte ints, right? But ints aren't 4 bytes (well, not necessarily, anyway: I once worked on a system where it would have been reasonable for CHAR_BITS == INT_BITS == 16, and plenty of systems a bit later with sizeof(int) == 2). Also, this is just duplicating the magicness in the comments: what is the first 4? And why not this?

    malloc( 4*sizeof(int)+1 ); // one int per season of year, 1 byte for trailer

    Now the comment explains what the magic number means.

    Sigh. Sense of humour fail.

    Dead arm! Humerus fail.

  • RBoy (unregistered) in reply to Bill's kid
    Bill's kid:
    argh:
    the beholder:
    public static final int INTEGER_FRIST = 1;

    Don't u guys ever sleep? Perhaps a new joke next time at least? Is it too much to ask?

    Apprently it is.

    I guess we have a new running joke, but Bert Glanstron isn't very funny or creative. At least the Frists (at least the proper frists) do show some creativity.

    OBTW.. I apologize if it's hard to read my comment, I have cold, and I fear that my typing is somewhat nisl sounding.

  • The Nerve (unregistered) in reply to Mr. Bob
    Mr. Bob:
    My eyes are burning. Is that the magic happening?

    No, that's probably the refresh rate on your monitor. Try increasing it.

  • wtf (unregistered) in reply to RBoy
    RBoy:

    I guess we have a new running joke, but Bert Glanstron isn't very funny or creative. At least the Frits (at least the proper frits) do show some creativity.

    Not often, he doesn't.

Leave a comment on “Avoiding Magic Constants”

Log In or post as a guest

Replying to comment #:

« Return to Article