Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

[Newbie Question] Magic Number's dangerous?

Thread view: 
seungwoo.yu@gmail.com - 25 Nov 2005 01:53 GMT
Hello, All

There are many magic numbers located in our java source code.
Someone pointed out that this is not good coding style.
What dangerous appeared? used Magic Numbers

Thanks
clarke.jonathan@gmail.com - 25 Nov 2005 03:18 GMT
hmm....Let me be the first to say "huh"?

perhaps your refering to the mythical magic number beast that lives
within the MS java VM.  Its sole mission is to eat decent java code?
Mike Gaab - 25 Nov 2005 04:08 GMT
> hmm....Let me be the first to say "huh"?
>
> perhaps your refering to the mythical magic number beast that lives
> within the MS java VM.  Its sole mission is to eat decent java code?

A magic number is simply a number in your source.
For example, let's say we were tracking days of a week.

short dayOfWeek = 4;

4 is a magic number. It really has no meaning, does it mean it is the 4th
day
of the week or the 5th day of the week? We don't know by just looking at
it. Surely we could find out by hunting through other source code but that
is
a waste of time. So we could do the following. [brute force but you
get the idea]

public static final short Sun= 0;
public static final short Mon = 1;
public static final short Tues = 2;
public static final short Wed   = 3;
public static final short Thurs= 4;
public static final short Fri = 5;
public static final short Sat = 6;
...
short dayOfWeek = Thur;

Now this makes the code easy to read and understand which makes your
code easier to maintain.

Mike
clarke.jonathan@gmail.com - 25 Nov 2005 05:18 GMT
Ahh ok.

Knew the concept however I never realised that it was known as Magic
Numbers.  Was someone in Sun smoking something at the time when they
came up with that name I wonder?
Gordon Beaton - 25 Nov 2005 06:39 GMT
> Knew the concept however I never realised that it was known as Magic
> Numbers.  Was someone in Sun smoking something at the time when they
> came up with that name I wonder?

It's a common term in computer programming and it predates Sun.

http://en.wikipedia.org/wiki/Magic_number_%28programming%29

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e

grubbyfans - 25 Nov 2005 14:21 GMT
though it takes place to store static final variables it's useful to
maintain the source code and modify
Monique Y. Mudama - 26 Nov 2005 00:13 GMT
> Ahh ok.
>
> Knew the concept however I never realised that it was known as Magic
> Numbers.  Was someone in Sun smoking something at the time when they
> came up with that name I wonder?

I don't even remember the first time I heard the term Magic Number.
I'm sure it didn't have any connection to Java, though.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Roedy Green - 26 Nov 2005 01:01 GMT
On Fri, 25 Nov 2005 17:13:52 -0700, "Monique Y. Mudama"
<spam@bounceswoosh.org> wrote, quoted or indirectly quoted someone who
said :

>I don't even remember the first time I heard the term Magic Number.
>I'm sure it didn't have any connection to Java, though.

I first heard the term  in the context of numbers you precalculated.
Today compilers can evaluate the corresponding expressions at compile
time.

There is a magic-number in the Class file format.  0xCAFEBABE.  It is
just a signature at the head to identify class files.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Alan Krueger - 26 Nov 2005 02:12 GMT
> There is a magic-number in the Class file format.  0xCAFEBABE.  It is
> just a signature at the head to identify class files.

A Unix version of Rational's Purify I once used filled uninitialized
memory with 0xDEADBEEF.
Chris Smith - 26 Nov 2005 16:22 GMT
> There is a magic-number in the Class file format.  0xCAFEBABE.  It is
> just a signature at the head to identify class files.

That is, of course, a completely different use of the phrase "magic
number".  The two have nothing to do with each other, except that they
are both numbers.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

zero - 25 Nov 2005 17:42 GMT
> public static final short Sun= 0;
> public static final short Mon = 1;
[quoted text clipped - 10 lines]
>
> Mike

Since 1.5 it might be better to use enums.

enum DayOfWeek { Sun, Mon, Tues, ...

Not sure how thos affects performance though, and for something simple this
may be overkill.
Thomas Hawtin - 25 Nov 2005 18:46 GMT
>>public static final short Sun= 0;
>>public static final short Mon = 1;
[quoted text clipped - 3 lines]
>>public static final short Fri = 5;
>>public static final short Sat = 6;

> Since 1.5 it might be better to use enums.
>
> enum DayOfWeek { Sun, Mon, Tues, ...
>
> Not sure how thos affects performance though, and for something simple this
> may be overkill.

Overkill? Seems to reduce quantity and improves clarity of the code.

Performance is unlikely to matter.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

zero - 25 Nov 2005 19:03 GMT
>>>public static final short Sun= 0;
>>>public static final short Mon = 1;
[quoted text clipped - 16 lines]
>
> Tom Hawtin

Probably, but I haven't seen any tests (or done any myself) so I'd rather
say that it *might* be an issue than just ignore it and possibly give
someone bad information.

Signature

Beware the False Authority Syndrome

Chris Smith - 26 Nov 2005 16:26 GMT
> Probably, but I haven't seen any tests (or done any myself) so I'd rather
> say that it *might* be an issue than just ignore it and possibly give
> someone bad information.

I agree that we should remember programmers generally have poor
intuition about performance.  However, the fact remains that all
programmers do have SOME intuition, and there are cases where that
intuition can be reasonably applied.

The overhead for declaring an enumerated type for the seven days of the
week cannot POSSIBLY be significant enough to merit any thought.  If it
were, then Sun would have failed miserably and it would be the buzz of
the Java world by now.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Roedy Green - 26 Nov 2005 19:40 GMT
>The overhead for declaring an enumerated type for the seven days of the
>week cannot POSSIBLY be significant enough to merit any thought.  If it
>were, then Sun would have failed miserably and it would be the buzz of
>the Java world by now.

I have done a fair bit of staring at decompiled enum code to figure
out how it works.

The crucial problem with type-safe enum kludges is getting a decently
fast SWITCH.  The Java enum implementors went to considerable
shenanigans to implement the switch with a plain old jump table using
a fast tableswitch JVM instruction instead of a lookupswitch.

It looks like this to ensure dense ints even for very large enums.
// use an ordinary int switch, using pre-mapped ordinals to sort the
switch.
     switch ( $switchMap[ breed.ordinal() ] )
        {
        case 1: // DASCHUND
           return true;

        case 2: // DALMATIAN
        case 3: // LABRADOR
        default:
           return false;
        }

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike Gaab - 25 Nov 2005 19:44 GMT
>>>public static final short Sun= 0;
>>>public static final short Mon = 1;
[quoted text clipped - 10 lines]
>
> Overkill? Seems to reduce quantity and improves clarity of the code.

I am not up on recent Java features but I did look at the enum type prior to
deciding to use named constants in the example above. Seemed to me like
using Java enums confused the issue as they don't appear to be implemented
as they are in many other languages. Not that implementing them differently
is a bad thing , just not implemented as one would expect. For instance, how
do I assign a value to each element?  What are the default values? In the
case above one could expect the values to be Sun=0, Mon=1 and so on but at a
quick glance they did not appear to have those values. How do I get at each
elements value to possibly re-assign its value?

Since you are up to speed on enums, how about an example.

Mike
Roedy Green - 25 Nov 2005 20:05 GMT
> For instance, how
>do I assign a value to each element?  What are the default values?

see http://mindprod.com/jgloss/enum.html
to answer your basic questions.

Java numbers them automatically.

If you want some other numbers or values, you can define a method and
implement it for each enum constant, or pass it is the constructor and
use a method common to all enum constants.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Lasse Reichstein Nielsen - 25 Nov 2005 21:59 GMT
> I am not up on recent Java features but I did look at the enum type prior to
> deciding to use named constants in the example above. Seemed to me like
> using Java enums confused the issue as they don't appear to be implemented
> as they are in many other languages. Not that implementing them differently
> is a bad thing , just not implemented as one would expect. For instance, how
> do I assign a value to each element?  

Like you assign values to other objects:
---
enum EnumWithAValue {
 FOO(2),
 BAR(42),
 BAZ(87);

 public final int value;
 EnumWithAValue(int value) {
   this.value = value;
 }
}

// .... FOO.value == 2
---
You can also assign more than one value to each instance.

> What are the default values?

There are none. The elements of an enumeration have nothing to
distinguish themselves by except their object identity (well, they do
have a name and an ordinal, but that's really implementation details).

> In the case above one could expect the values to be Sun=0, Mon=1 and
> so on but at a quick glance they did not appear to have those
> values.

Correct. Java enumerations define a type with a fixed number of
values. It does so using a class with a fixed number of instances.

C-like languages instead define a fixed number of integer constants.
There is no type, so you cannot declare a variable to only take
members of the enumeration as values. I.e., the Java way is type-safe,
the C one is not.

The Java enumeration implementation is taken from the way people were
already implementing type-safe enums. It was explained in, e.g.,
"Java Language Programming Guide" by Joshua Bloch (Item 21 IIRC).

> How do I get at each elements value to possibly re-assign
> its value?

If you really want to be able to change it, make a settable value on
each instance. Otherwise, just set value by the constructor.

It really is just a class and instances of it. What makes it an enum
is that there can only be a fixed number of instances. (A singleton
is really just a trivial enumeration)

/L
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Hendrik Maryns - 28 Nov 2005 10:16 GMT
Mike Gaab schreef:
<snip>
> I am not up on recent Java features but I did look at the enum type prior to
> deciding to use named constants in the example above. Seemed to me like
> using Java enums confused the issue as they don't appear to be implemented
> as they are in many other languages. Not that implementing them differently
> is a bad thing , just not implemented as one would expect.
It´s more like, the old-style enums are implemented in a very primitive way.
For instance, how
> do I assign a value to each element?  
Why would you want to?
What are the default values?
Why do you care?
In the
> case above one could expect the values to be Sun=0, Mon=1 and so on but at a
> quick glance they did not appear to have those values. How do I get at each
> elements value to possibly re-assign its value?
Again, why would you want to?

IM(H)O, if you explicitly assign values to (Java´s) enum constants, you
don´t get the idea of what enums are for.

H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

Mike Gaab - 28 Nov 2005 15:20 GMT
Mike Gaab schreef:
<snip>
> I am not up on recent Java features but I did look at the enum type prior
> to deciding to use named constants in the example above. Seemed to me like
> using Java enums confused the issue as they don't appear to be implemented
> as they are in many other languages. Not that implementing them
> differently is a bad thing , just not implemented as one would expect.
It´s more like, the old-style enums are implemented in a very primitive way.
For instance, how
> do I assign a value to each element?
Why would you want to?
What are the default values?
Why do you care?
In the
> case above one could expect the values to be Sun=0, Mon=1 and so on but at
> a quick glance they did not appear to have those values. How do I get at
> each elements value to possibly re-assign its value?
Again, why would you want to?

IM(H)O, if you explicitly assign values to (Java´s) enum constants, you
don´t get the idea of what enums are for.

H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

Roedy Green - 28 Nov 2005 17:54 GMT
>> do I assign a value to each element?
>Why would you want to?
>What are the default values?
>Why do you care?

lots of reasons.  An enum can have associated with it such things as:
1. aliases
2. long form English text
3. compact persistent representations for databases
4. boolean properties
5. associated files
6. associated methods

Stop thinking of enums in the C-like way and think of them more
high-level.

So for example, if you have 12 different recording formats, each
represented  by an enum, what other data do you want about each enum.
Here are some ideas:
1. name
2. mime type
3. typical extensions.
4. readers that handle it
5. icon to represent it in HTML
6. proprietary?
7. URL of format definer
8. checksum computer
9. min/max frequency

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Hendrik Maryns - 29 Nov 2005 10:20 GMT
Roedy Green schreef:

>>>do I assign a value to each element?
>>
[quoted text clipped - 12 lines]
> Stop thinking of enums in the C-like way and think of them more
> high-level.

I am, I never used C enums.  But this was a reaction to the question why
you can´t change the enum value.  That is something entirely different
than the things you propose here, and which I totally agree to.  Only,
they should be stictly separated from the internal enum constant value.

> So for example, if you have 12 different recording formats, each
> represented  by an enum, what other data do you want about each enum.
[quoted text clipped - 8 lines]
> 8. checksum computer
> 9. min/max frequency

Good example.  And again, this cannot be expressed by one single value
which is accidentally the value with which the enum constant is
recognised internally.

I hope this is an answer to Mike´s question too.

H.

Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

Roedy Green - 29 Nov 2005 11:21 GMT
On Tue, 29 Nov 2005 11:20:18 +0100, Hendrik Maryns
<hendrik_maryns@despammed.com> wrote, quoted or indirectly quoted
someone who said :

>Only,
>they should be stictly separated from the internal enum constant value.

You keep thinking in C.  There is no value to assign.  The enum value
is a reference to an enum constant object. The closest thing to the
C-style value is the ordinal -- automatically assigned by counting off
the enum objects.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Hendrik Maryns - 29 Nov 2005 11:31 GMT
Roedy Green schreef:
> On Tue, 29 Nov 2005 11:20:18 +0100, Hendrik Maryns
> <hendrik_maryns@despammed.com> wrote, quoted or indirectly quoted
[quoted text clipped - 7 lines]
> C-style value is the ordinal -- automatically assigned by counting off
> the enum objects.

That´s what I meant, just don´t know the terminology.  And I never
mentioned the word `assign´.  Anyway, I really do agree with you.

H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

Mike Gaab - 29 Nov 2005 16:11 GMT
> wrote, quoted or indirectly quoted someone who said :

>>I hope this is an answer to Mike´s question too.

I'm getting there but slowly.
Thanks, Mike

Mike Gaab - 28 Nov 2005 15:30 GMT
>>IM(H)O, if you explicitly assign values to (Java´s) enum constants, you
>>don´t get the idea of what enums are for.

Could be.
Please explain what you think I am not understanding.

Mike
Roedy Green - 28 Nov 2005 17:57 GMT
>>>IM(H)O, if you explicitly assign values to (Java´s) enum constants, you
>>>don´t get the idea of what enums are for.
>
>Could be.
>Please explain what you think I am not understanding.

Enums values are enum constant objects.  This is how type safety is
maintained so you don't pass a gender enum to a
favouriteFlavourOfIceCream parameter.

Enums have automatically assigned sequential  ordinals ( similar to
the values assigned manually C ).  You can of course have fields and
methods to add C-style non-sequential ints as well.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike Gaab - 26 Nov 2005 02:16 GMT
>>>public static final short Sun= 0;
>>>public static final short Mon = 1;
[quoted text clipped - 10 lines]
>
> Overkill? Seems to reduce quantity and improves clarity of the code.

From what I have seen from other posters especially Lasses' post,
I totally disagree. Enums are very OO but, IMO, far from more readable
than a simple named constant. My preference would be to use named
constants but I am not saying there isn't a useful application of Java
enums.

Mike
Alan Krueger - 27 Nov 2005 18:16 GMT
> From what I have seen from other posters especially Lasses' post,
> I totally disagree. Enums are very OO but, IMO, far from more readable
> than a simple named constant. My preference would be to use named
> constants but I am not saying there isn't a useful application of Java
> enums.

Let's turn this around.  Is it *less* readable that a simple named
constant?  It's certainly less type-safe.  You can have completely
readable, compilable code that's entirely wrong.
Roedy Green - 27 Nov 2005 18:22 GMT
> IMO, far from more readable
>than a simple named constant. My preference would be to use named
>constants but I am not saying there isn't a useful application of Java
>enums.

But to the client of the enum, the enum constant looks almost
identical to the old C style named constant.  It just points to an
object instead of an int for type safety. You use them almost the same
way.

Before you give up on enum, try them out for some simple project. They
are definitely peculiar, but they do work reasonably well in practice.

see http://mindprod.com/jgloss/enum.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 27 Nov 2005 18:23 GMT
> IMO, far from more readable
>than a simple named constant. My preference would be to use named
>constants but I am not saying there isn't a useful application of Java
>enums.

I quite like them.  They are much more than just a replacement for C
style enums.  They are a way of wrapping all kind of auxiliary facts
around the enum in an OO way.  It makes for much tidier and shorter
code.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike Gaab - 25 Nov 2005 03:18 GMT
> Hello, All
>
[quoted text clipped - 3 lines]
>
> Thanks

IMO, the worst thing is that it makes your code hard to read, and
therefore it is hard to understand. Numbers standing alone communicate
little to nothing except for a maybe a 0 or 1. Then it follows that your
code will be hard to maintain and can be error prone.

That's my two cents worth.
Mike
Roedy Green - 25 Nov 2005 05:56 GMT
>There are many magic numbers located in our java source code.
>Someone pointed out that this is not good coding style.
>What dangerous appeared? used Magic Numbers

The problem is in maintenance.  If someone changes them they may
change literals in not enough or too many places.  With named
constants there is one place to fix and it is clearly labelled what
the constant means.  In context in code it is not as clear.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

josh.s17@gmail.com - 26 Nov 2005 06:04 GMT
I have noticied a trend recently that programmers don't treat Magic
numbers in JSP code in the same way as magic numbers in straight java.
In my opinion magic numbers anywhere are bad and should be avioded.
Thomas Hawtin - 25 Nov 2005 14:50 GMT
> There are many magic numbers located in our java source code.
> Someone pointed out that this is not good coding style.
> What dangerous appeared? used Magic Numbers

It is often the case that programmers get over draconian when it comes
to magic numbers. With a new hammer, everything becomes a nail.

If you need to allocate a buffer, it's better to write:

    byte[] buff = new byte[8192];

(and use buff.length rather than repeating the number) than to write:

    /**
     * Size of buffer private to {@link #xyzFunction}.
     */
    private static final SOME_BUFFER_LENGTH = 8192;

... screens later ...

    byte[] buff = new byte[SOME_BUFFER_LENGTH];

As a rule of thumb, if a number *or string* appears twice, always give
it a constant (or preferably eliminate subsequent appearances). For
other cases, use common sense.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Alan Krueger - 25 Nov 2005 15:31 GMT
> If you need to allocate a buffer, it's better to write:
>
[quoted text clipped - 10 lines]
>
>     byte[] buff = new byte[SOME_BUFFER_LENGTH];

In my experience, this seems to be a carryover from coding in C/C++
where you can't always tell the size of a buffer from the buffer itself.
 But this, then, fires the rule you mention next:

> As a rule of thumb, if a number *or string* appears twice, always give
> it a constant (or preferably eliminate subsequent appearances). For
> other cases, use common sense.

But only if the number or string has the same semantic meaning.  If two
numbers appear and happen to be the same value, but one could change
independently of the other, it doesn't make sense to artificially tie
them together.

I know, that should fall under the common sense, but as in other things,
common sense isn't as common as it should be.
Gordon Beaton - 25 Nov 2005 14:41 GMT
> But only if the number or string has the same semantic meaning. If
> two numbers appear and happen to be the same value, but one could
[quoted text clipped - 3 lines]
> I know, that should fall under the common sense, but as in other
> things, common sense isn't as common as it should be.

I remember discovering the following during a code review:

 #define ONE 1
 #define TWO 2
 #define THREE 3
 [...]

...all the way to a hundred or so.

I asked the programmer if he thought that any of these values might
need to change one day (no), or if he could tell me what any of them
meant (only by looking at the code where they were used).

Nobody had ever explained to him the *purpose* of using symbolic
constants, just that it was a bad idea to have the values themselves
directly in the code.

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e

Roedy Green - 25 Nov 2005 19:50 GMT
>I remember discovering the following during a code review:
>
>  #define ONE 1
>  #define TWO 2
>  #define THREE 3
>  [...]

LOL.  I have added that one to
http://mindprod.com/jgloss/unmainotherpeople.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Gordon Beaton - 26 Nov 2005 17:05 GMT
> LOL.  I have added that one to
> http://mindprod.com/jgloss/unmainotherpeople.html

That's fine, but he wasn't a clever programmer rebelling against
anything. He was rather inexperienced and was simply following a rule
he had been taught without really understanding it.

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e

Roedy Green - 26 Nov 2005 21:32 GMT
>That's fine, but he wasn't a clever programmer rebelling against
>anything.

that is part of the fiction of the essay -- that writing
unmaintainable code is done deliberately, and this is a how to essay.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Monique Y. Mudama - 26 Nov 2005 00:11 GMT
>> But only if the number or string has the same semantic meaning. If
>> two numbers appear and happen to be the same value, but one could
[quoted text clipped - 22 lines]
>
> /gordon

Eek.

I had to work with code that had some brilliant lines:

#define PKT_TEN 10
#define PKT_FIFTEEN 15
#define PKT_TWNTYTWO 22
#define PKT_TWENTYTHREE 23

Yes, not only did the previous dev hard-code these numbers, he
actually spelled twenty differently in various packet names.

So then I got to go tracing through the code, trying to figure out
what the heck packet 15 did, anyway.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Monique Y. Mudama - 26 Nov 2005 00:22 GMT
> I had to work with code that had some brilliant lines:
>
[quoted text clipped - 8 lines]
> So then I got to go tracing through the code, trying to figure out
> what the heck packet 15 did, anyway.

I forgot to mention the fun part: he and I ended up working on
different projects, but anyway, I got laid off, and he didn't.

My co-workers were livid.  (He was infamous for writing awful,
unmaintainable code, so much so that there was a name for his awful
code derived from his last name.)

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Mike Gaab - 26 Nov 2005 01:11 GMT
>>> But only if the number or string has the same semantic meaning. If
>>> two numbers appear and happen to be the same value, but one could
[quoted text clipped - 37 lines]
> So then I got to go tracing through the code, trying to figure out
> what the heck packet 15 did, anyway.

Hi Monique,

(I love that name. :-) )

Just curious, what would have been a better naming scheme?
Sometimes it is really hard to come up with one.

Mike
Roedy Green - 25 Nov 2005 19:44 GMT
On Fri, 25 Nov 2005 09:31:37 -0600, Alan Krueger
<wgzkid502@sneakemail.com> wrote, quoted or indirectly quoted someone
who said :

>I know, that should fall under the common sense, but as in other things,
>common sense isn't as common as it should be.

Applause! Did you make that up?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Alan Krueger - 26 Nov 2005 02:16 GMT
> On Fri, 25 Nov 2005 09:31:37 -0600, Alan Krueger
> <wgzkid502@sneakemail.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 4 lines]
>
> Applause! Did you make that up?

No, it's an observation.  How many times have you heard people say
something should be common sense in the context of someone having not
used it?
Roedy Green - 26 Nov 2005 21:38 GMT
On Fri, 25 Nov 2005 20:16:01 -0600, Alan Krueger
<wgzkid502@sneakemail.com> wrote, quoted or indirectly quoted someone
who said :

>>>I know, that should fall under the common sense, but as in other things,
>>>common sense isn't as common as it should be.
[quoted text clipped - 4 lines]
>something should be common sense in the context of someone having not
>used it?

I have added that quote to my collection.  We'll see if it passes by
osmosis into other collections,  a little bid for immortality.

See http://mindprod.com/ethics/quote.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Monique Y. Mudama - 26 Nov 2005 00:09 GMT
>> There are many magic numbers located in our java source code.
>> Someone pointed out that this is not good coding style.
[quoted text clipped - 17 lines]
>
>      byte[] buff = new byte[SOME_BUFFER_LENGTH];

Seems like you're dodging the issue here by giving a poor example.
The fact is that you must have chosen 8192 for a reason, and that
reason can be documented with a well-chosen variable name.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Chris Smith - 26 Nov 2005 16:36 GMT
> >      byte[] buff = new byte[8192];
> >
> >      byte[] buff = new byte[SOME_BUFFER_LENGTH];

> Seems like you're dodging the issue here by giving a poor example.
> The fact is that you must have chosen 8192 for a reason, and that
> reason can be documented with a well-chosen variable name.

Nah, I don't see that that's necessarily the case.  When choosing buffer
sizes, it's generally a matter of taking a guess.  Usually, the guess is
a power of two, because it works better with MMU/paging architectures
where memory is typically allocated in pages of a power of two in size.  
Tuning can be done later if it becomes a performance problem of some
kind.  If there's some other kind of ultimate method of calculating
ideal buffer sizes, then most of us haven't yet been informed.

I typically choose buffers of size 32768 unless I have some reason not
to.  Obviously, Thomas Hawtin commonly uses 8192.  Why?  No particular
reason.  If it starts mattering in a measurable way, then I'm sure
they'll get tuned, and then a comment will be added explaining the
method used to choose the buffer size and the observed consequences of
making it too large/small.

In any case, even if the buffer size is carefully tuned, I very much
doubt that you could explain the method or logic behind the choice in a
reasonable identifier name.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Monique Y. Mudama - 06 Dec 2005 21:44 GMT
>> >      byte[] buff = new byte[8192];
>> >
[quoted text clipped - 23 lines]
> doubt that you could explain the method or logic behind the choice
> in a reasonable identifier name.

Sorry for the late reply.

What if you get run over by a bus?  The next guy to look at your code
won't know if you chose 32768 because it's your favorite number or
because you found it to be the best via experimentation.  So the new
guy will probably avoid touching the magic 32768, whereas at least a
comment that "I pulled this number from my orifice; feel free to tweak
as needed" would give the guy some insight.

And as soon as you find that you need to pass the buffer chunks around,
it's better to use a constant instead of hard-coding the number in
several places.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Chris Smith - 06 Dec 2005 22:22 GMT
> Sorry for the late reply.

No problem.

> What if you get run over by a bus?  The next guy to look at your code
> won't know if you chose 32768 because it's your favorite number or
> because you found it to be the best via experimentation.  So the new
> guy will probably avoid touching the magic 32768, whereas at least a
> comment that "I pulled this number from my orifice; feel free to tweak
> as needed" would give the guy some insight.

Well, I sorta operate the other way around.  If there isn't a comment by
a buffer size, then I'd assume it's safe to tweak.  Certainly someone
who did the testing and did not bother to document the results would be
negligent at a minimum.

Regardless, this isn't really relevant to the desire to use an
identifier.  You don't explain benchmarking results in identifier names.  
(At least, hopefully you don't.)

> And as soon as you find that you need to pass the buffer chunks around,
> it's better to use a constant instead of hard-coding the number in
> several places.

No, that's absolutely not the case.  When I pass that buffer around, it
carries with it the size.  All someone needs to do is write
"buffer.length" and, voila, they've discovered the length of the buffer!

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Monique Y. Mudama - 06 Dec 2005 23:07 GMT
>> What if you get run over by a bus?  The next guy to look at your
>> code won't know if you chose 32768 because it's your favorite
[quoted text clipped - 8 lines]
> Certainly someone who did the testing and did not bother to document
> the results would be negligent at a minimum.

I guess I've worked with a lot of brittle and poorly documented code.
A lot of times, I was working with code written by people who were not
great at software, but understood the problem domain (Aerospace and
all of its fiddly bits) better than I did.  An experienced Aerospace
person might (did) often assume that it's "obvious" why this was the
right number ...  and I had no idea.

> Regardless, this isn't really relevant to the desire to use an
> identifier.  You don't explain benchmarking results in identifier
> names.  (At least, hopefully you don't.)

Okay, true.  Names are just one type of breadcrumb.  I'm a strong
advocate of breadcrumbs =)

>> And as soon as you find that you need to pass the buffer chunks
>> around, it's better to use a constant instead of hard-coding the
[quoted text clipped - 4 lines]
> "buffer.length" and, voila, they've discovered the length of the
> buffer!

Ah, yeah!  I guess I was thinking of other languages ...

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Oliver Wong - 07 Dec 2005 20:38 GMT
>>> What if you get run over by a bus?  The next guy to look at your
>>> code won't know if you chose 32768 because it's your favorite
[quoted text clipped - 15 lines]
> person might (did) often assume that it's "obvious" why this was the
> right number ...  and I had no idea.

<fable>
Person A inherits some code from somewhere, and sees an array which is
declared to be of size 1073. Why 1073? He does a quick search and sees that
1073 never appears anywhere else in the source code. So he pours through the
code and eventually figures out that the array is being used as a hashtable,
and that the hashing function being used generates fewer collisions when the
size of the table is a prime number, so Person A declares a new constant:

#DEFINE SOME_PRIME_NUMBER 1073

A few years later, Person Z inherits the code long after Person A has passed
it on to someone else, who has then passed it on to someone else, who has
passed it on to someone else, etc. This was back in the days before
versioning systems, so there was no way for Person Z to know that there
existed a Person A who made changes, nevermind what those changes were.

So Person Z goes through the code, and sees the following line:

#DEFINE SOME_PRIME_NUMBER 1073

And he says to himself "WTF? 1073 = 23*37. How is that prime?" He changes
the value to 1087, which IS a prime number.

#DEFINE SOME_PRIME_NUMBER 1087

Ever since that day, the code has been breaking in subtle and mysterious
ways.
</fable>

   - Oliver
Thomas Hawtin - 07 Dec 2005 20:56 GMT
> #DEFINE SOME_PRIME_NUMBER 1073
>
> And he says to himself "WTF? 1073 = 23*37. How is that prime?" He changes
> the value to 1087, which IS a prime number.

It would be easier to just add a zero in front of the number.

#define SOME_PRIME_NUMBER 01073

Sorted. Proper maintenance craftsmanship.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Oliver Wong - 07 Dec 2005 22:12 GMT
>> #DEFINE SOME_PRIME_NUMBER 1073
>>
[quoted text clipped - 6 lines]
>
> Sorted. Proper maintenance craftsmanship.

   Nice.

   But the advantage of using 1087 is that it is a bigger number than the
previous one, and thus less likely to result in
ArrayIndexOutOfBoundsException, or whatever the C equivalent to that is.

   - Oliver
Chris Uppal - 07 Dec 2005 23:20 GMT
> Sorted. Proper maintenance craftsmanship.

<wild applause/>

   -- chris
Mike Schilling - 07 Dec 2005 01:37 GMT
>> And as soon as you find that you need to pass the buffer chunks around,
>> it's better to use a constant instead of hard-coding the number in
[quoted text clipped - 3 lines]
> carries with it the size.  All someone needs to do is write
> "buffer.length" and, voila, they've discovered the length of the buffer!

I misread Monique's comment as "And if you want to create the same-sized
buffer in multiple places...", which is a good reason, even in Java.

In general, I obey the principal that 0 and 1 are the only unnamed numeric
constants I use.
Chris Smith - 07 Dec 2005 02:52 GMT
> I misread Monique's comment as "And if you want to create the same-sized
> buffer in multiple places...", which is a good reason, even in Java.

And in that case (that is, if it really MATTERS that the two buffers be
the same size), there is also likely to be a good symbolic name that
expresses the significance of that number.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Monique Y. Mudama - 07 Dec 2005 05:19 GMT
> I misread Monique's comment as "And if you want to create the
> same-sized buffer in multiple places...", which is a good reason,
> even in Java.
>
> In general, I obey the principal that 0 and 1 are the only unnamed
> numeric constants I use.

I do have some magic numbers in the code I'm currently maintaining, but
they are commented as such.  For example, through experimentation I
found that 4 was a good starting point for getting an aesthetically
pleasing number of labels on the Y axis for our particular graph.  So I
use the number 4, but I do have a comment explaining why it's there and
that it's not sacred.

I'm just a big fan of leaving a breadcrumb trail for others (or my later
self) to follow.  Some indication of the thought process that resulted
in the current code.  I recognize that sometimes, time constraints
don't allow me to use the best possible design or flow, but I like to
at least sprinkle comments to that effect.

I absolutely hate the dreaded "But you can't put comments indicating the
code might be flakey; the customer might see it and realize we're not
perfect!" whine from managers.  Fortunately not an issue in my current
project.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Chris Uppal - 07 Dec 2005 12:26 GMT
> Well, I sorta operate the other way around.  If there isn't a comment by
> a buffer size, then I'd assume it's safe to tweak.

Especially when:
   a) it's used for the size of a buffer or similar;
   b) it's an obviously arbitrary value such as an unimportant power of two.

Values I'd be more cautious about tweaking (in the absence of further
information):
   137    (not a power of two)
   256    (may be 2**number-of-bit-in-a-byte)
   8097  (not a power of two)

Values I would tweak:
   8096
   8096+1  (wouldn't change the +1 but would tweak the 8096).
   1024 * <almost anything>

OTOH, I wonder how much old 'C' software is now using undersized buffers (and
similar) because the old code didn't:
   #define BIG_BUFFER_SIZE (8 * 1024)
   #define BUFFER_SIZE (2*1024)
   #define SMALL_BUFFER_SIZE 512
which could nowadays be updated to use much bigger numbers while still
respecting the intent of the author.

   -- chris
Chris Smith - 26 Nov 2005 16:48 GMT
> As a rule of thumb, if a number *or string* appears twice, always give
> it a constant (or preferably eliminate subsequent appearances). For
> other cases, use common sense.

As Monique implied, there are really two reasons to use a named
constant: (a) it's duplicated, and (b) it can be given a simple name
that's more descriptive than the number itself.  You have absorbed case
(b) into "common sense", but IMO it's worth being explicit about.

A lot of programming "rules" like this are based on assuming that (b) --
or its analogue in another code decision -- is true.  A lot of the
zealous over-application of these rules comes from people being
unwilling or unaware of the need to make a decision about the truth of
(b).

Ultimately, I'm agreeing with you.  There are cases where a number,
properly put into context, is simply more expressive than any possible
logic about where it comes from.

That logic is either clear from the usage, as in:

   if (mode.equals("biped")) numLegs = 2;
   else numLegs = 4;

   (versus)

   final int BIPED_LEGS = 2;
   final int QUADRUPED_LEGS = 4;

   if (mode.equals("biped")) numLegs = BIPED_LEGS;
   else numLegs = QUADRUPED_LEGS;

or it can't be expressed in an identifier anyway, as in:

   /*
    * According to Dr. Seorge in his 1992 paper in "Transactions of
    * the American Journal of Rocket Science", the amount of fuel
    * should be calculated by this formula:
    */
   double amountOfFuel = 14.97264 / (1.493 + numEngines + numFins);

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Monique Y. Mudama - 26 Nov 2005 00:18 GMT
> Hello, All
>
[quoted text clipped - 3 lines]
>
> Thanks

There are a few reasons.

One: at the moment you write the code, you may know very well that 3
represents the number of holes you expect to see in a piece of
notebook paper.  But six months from now,

NUM_HOLES_IN_PAPER

is much clearer than

3.

If I've seen one thing in my career, it's that what is "obvious" today
is completely opaque in a few months.

Two: What if you have several classes that have to know how many holes
are in a piece of notebook paper?  If you hard-code '3' into several
files, life will be hard when your paper source changes to 2-hole
paper. Also, in every place where '3' is used, you will have to think
about whether '3' represents the number of holes in paper, or whether
it actually represents the number of toner cartridges you had
available.  Or whatever.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.