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 / July 2006

Tip: Looking for answers? Try searching our database.

Style of coding

Thread view: 
howachen@gmail.com - 04 Jul 2006 17:36 GMT
Consider the following styles, which one is preferred....

1.
public class Person {

    private String name;

    public void setName(String n) {
        this.name = n;
    }
}

2.
public class Person {

    private String name;

    public void setName(String n) {
        name = n;
    }
}

and...if in case of static ....

3.
public class Person {

    private static String name;

    public static void setName(String n) {
        Person.name = n;
    }
}

4.
public class Person {

    private static String name;

    public static void setName(String n) {
        name = n;
    }
}

1 or 2

3 or 4 ?
Stefan Ram - 04 Jul 2006 17:46 GMT
>Consider the following styles, which one is preferred....
>public class Person {
>    private String name;

public class Person
{ private java.lang.String name;
 public void setName( final java.lang.String name )
 { this.name = name; }}
howachen@gmail.com - 04 Jul 2006 17:50 GMT
Stefan Ram

> >Consider the following styles, which one is preferred....
> >public class Person {
[quoted text clipped - 4 lines]
>   public void setName( final java.lang.String name )
>   { this.name = name; }}

hi again :)

it is quite rare to see people to use the "final" keyword, what is the
exact advantage of doing so?

thanks again!
Oliver Wong - 04 Jul 2006 17:59 GMT
> it is quite rare to see people to use the "final" keyword, what is the
> exact advantage of doing so?

   It indicates that you don't intend for the value to change. This can
help you catch, at compile time, code which erroneously changes the value of
those variables.

   Also, anonymous inner classes can only access surrounding local
variables if they are final.

   - Oliver
howachen@gmail.com - 04 Jul 2006 18:01 GMT
Oliver Wong

> > it is quite rare to see people to use the "final" keyword, what is the
> > exact advantage of doing so?
[quoted text clipped - 7 lines]
>
>     - Oliver

thanks...then using "final" is really a good practice that every java
programmer should know....

btw, any comment on the style of static class as above?
Oliver Wong - 04 Jul 2006 18:42 GMT
> btw, any comment on the style of static class as above?

   Not really. I usually prefer to fully qualify names (which means using
"this." or the classname when appropriate), but some of my coworkers prefer
not to. It looks like I'm not bothered by really long identifier names at
all, while they are.

   - Oliver
Stefan Ram - 04 Jul 2006 18:51 GMT
>    Not really. I usually prefer to fully qualify names (which means using
>"this." or the classname when appropriate), but some of my coworkers prefer

 I am extreme in this regard. I always prefer the full path and
 never use »import«. So I write »java.lang.System.out.println«.

 I also like descriptive names.
 Recently I modified my Java-preprocessor: Now, I can write:

boolean 'can be extended by'( final int cp );

 My preprocessor will convert this to

boolean canBeExtendedBy( final int cp );

 (It usually will leave character literals untouched.)
Chris Uppal - 04 Jul 2006 19:01 GMT
>   I am extreme in this regard. I always prefer the full path and
>   never use »import«. So I write »java.lang.System.out.println«.

Now that /is/ extreme.  I'm on record as opining that import can be over-used
(and hence that wildcard imports are a Good Thing), but even in my most
pedantic moments, I would not dream of going quite that far ;-)

>   I also like descriptive names.
>   Recently I modified my Java-preprocessor: Now, I can write:
[quoted text clipped - 4 lines]
>
> boolean canBeExtendedBy( final int cp );

A perfectly reasonable name in itself, so I'm a bit puzzled by the need for a
preprocessor for it -- presumably converting 'can be extended by'() into
canBeExtendedBy() is only a small part of what it does ?

   -- chris
Stefan Ram - 04 Jul 2006 19:25 GMT
>> boolean 'can be extended by'( final int cp );
>>   My preprocessor will convert this to
[quoted text clipped - 3 lines]
>'can be extended by'() into canBeExtendedBy() is only a small
>part of what it does ?

 The notation with spaces looks more readable to me.

 Maybe examples with even longer names can show this:

void 'set start state to false'(){ this.start = false; }

public void advance( final java.lang.String text )
{ this.'set start state to false'();
 this.offset += text.length() - 1; this.justify(); }

 /* ... */

if( token.'can be extended by'( cursor1.'code point' ))
{ cursor1.advance(); looping = cursor1.'is within source text'(); }

 /* ... */

 I am using the general preprocessor gpp for most purposes

http://www.nothingisreal.com/gpp/

 while the feature mentioned to convert 'can be extended by'
 to 'canBeExtendedBy' is added via a Perl script.
Chris Uppal - 04 Jul 2006 19:01 GMT
> > it is quite rare to see people to use the "final" keyword, what is the
> > exact advantage of doing so?
>
>     It indicates that you don't intend for the value to change. This can
> help you catch, at compile time, code which erroneously changes the value
> of those variables.

Or, to put that another way, it's a waste of time when used for a parameter or
local variable.

If you don't want to change the value of a local variable, then don't change
it...

>     Also, anonymous inner classes can only access surrounding local
> variables if they are final.

True, and that /is/ a valid and important use.

   -- chris
Mike Schilling - 04 Jul 2006 23:55 GMT
>> > it is quite rare to see people to use the "final" keyword, what is the
>> > exact advantage of doing so?
[quoted text clipped - 10 lines]
> change
> it...

Put yet another way, if you need to document that the value of a local
variable doesn't change in a method, the method is too long:

   int setValue(final int newval)
   {
       val = newval;
   }

Does"final" tell you anything you didn't already know?

"final" might be of some use if it meant that the object referenced by the
variable wasn't changed by the method, but Java doesn't have that concept.
Stefan Ram - 05 Jul 2006 00:07 GMT
>Put yet another way, if you need to document that the value of a local
>variable doesn't change in a method, the method is too long:
[quoted text clipped - 3 lines]
>        val = newval;
>    }

 You have declared that the method returns an »int«, yet you do
 not return an int. The compiler will help you by issuing an
 error report. Obviously, the brevity of this method did not
 help you to avoid this mistake, which contradicts your claim.
Mike Schilling - 05 Jul 2006 07:21 GMT
>>Put yet another way, if you need to document that the value of a local
>>variable doesn't change in a method, the method is too long:
[quoted text clipped - 8 lines]
>  error report. Obviously, the brevity of this method did not
>  help you to avoid this mistake, which contradicts your claim.

:-)

When actually coding, I take more care than when dashing off a Usenet
posting, of course.
AndrewMackDonna - 05 Jul 2006 00:08 GMT
>>>> it is quite rare to see people to use the "final" keyword, what is the
>>>> exact advantage of doing so?
[quoted text clipped - 21 lines]
> "final" might be of some use if it meant that the object referenced by the
> variable wasn't changed by the method, but Java doesn't have that concept.

I find the biggest problem with 'final' is the mis-understanding it
creates.  People new to the language fail to realise it isn't a
protection mechanism for the object, as in c++'s Const.

Then even when you do point out that its only concerning the reference
or primitive, lots still seem to to think its a good 'design marker'  as
in...  "We know it does't protect the object, only the ref, but by
putting it here, you know I dont want you changing the state of the
object either".

other that class constants and refs for passing to threads, I dont use
them at all.
Stefan Ram - 04 Jul 2006 18:00 GMT
>>public void setName( final java.lang.String name )
>it is quite rare to see people to use the "final" keyword, what is the
>exact advantage of doing so?

 It is intended to be somewhat similar to the »in« in Ada:

procedure Average(A, B : in Integer; Result : out Integer);

 (That was Ada, not Java.)

 It expresses my intention only to read from the parameter and
 not to change the binding of the name »name« - though, of
 course, the semantics of the »final« in Java are not the same
 as those of »in« in Ada or »const« in C.

 If I would inadvertently change the in-Parameter, the compiler
 could issue a warning. But it also helps human readers to
 grasp my intention never to change the binding of the
 name »name« within this method declaration.
Bent C Dalager - 04 Jul 2006 22:36 GMT
>>>public void setName( final java.lang.String name )
>>it is quite rare to see people to use the "final" keyword, what is the
[quoted text clipped - 15 lines]
>  grasp my intention never to change the binding of the
>  name »name« within this method declaration.

In Java, whether or not a parameter is "final" is of no interest
whatsoever to the caller of the method:

- A method can never change the in-parameters themselves (as seen by
the caller), whether or not the parameter is declared as "final". That
is, all parameters are always passed by value, none are passed by
reference.

- A method can always change the contents of any object whose
reference is passed to it, whether or not the object reference
parameter is declared as "final". (*)

The "final"-ness of a parameter is only relevant to the internal
implementation of the method itself. I personally consider it an
unfortunate quirk of the language that this information is exposed to
client code.

Personally, I would have preferred all parameters to be defined by the
JLS to always be final. It would do away with the above quirk and it's
generally not such a good idea to start altering the method's
parameters anyway (in my experience, this is most often indicative of
some sort of bug and tends to make for less maintainable code even
when it is not).

* - Assuming the class involved is mutable, of course.

Cheers
    Bent D
Signature

Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd
                                   powered by emacs

Stefan Ram - 04 Jul 2006 22:46 GMT
>The "final"-ness of a parameter is only relevant to the internal
>implementation of the method itself. I personally consider it an
>unfortunate quirk of the language that this information is exposed to
>client code.

 It does not have to appear in the interface:

interface alpha { void beta( int delta ); }

class gamma implements alpha { void beta( final int delta ){} }
Stefan Ram - 04 Jul 2006 22:49 GMT
>The "final"-ness of a parameter is only relevant to the internal
>implementation of the method itself. I personally consider it an
>unfortunate quirk of the language that this information is exposed to
>client code.

 It does not have to appear in the interface:

interface alpha { void beta( int delta ); }

class gamma implements alpha { public void beta( final int delta ){} }
Dale King - 05 Jul 2006 08:57 GMT
> Stefan Ram 寫道:
>
[quoted text clipped - 10 lines]
> it is quite rare to see people to use the "final" keyword, what is the
> exact advantage of doing so?

Others have told you about final in the general case but here it has a
very specific usage.

Imagine if you wrote this:

   public void setName( java.lang.String name )
   {
       name = name;
   }

and left off the this. Making it final would give you an error in this case.

Unfortunately it is more common to do something like this:

   public void setReallyLongVariableName
       ( final java.lang.String reallyLongVaraibleName )
   {
       this.reallyLongVariableName = reallyLongVariableName ;
   }

There is a typo in the parameter name and this method ends up doing
absolutely nothing.

I use Eclipse which has a check you can turn on for finding these
"do-nothing" statements which would catch both errors.

Signature

 Dale King

AlecB - 07 Jul 2006 00:13 GMT
howachen@gmail.com was heard to mumble on 04.07.2006 18:50:
> Stefan Ram 寫道:
>
[quoted text clipped - 12 lines]
>
> thanks again!

I seem to recall it's a compiler optimisation.

Alec
IchBin - 04 Jul 2006 17:55 GMT
> Consider the following styles, which one is preferred....
>
[quoted text clipped - 43 lines]
>
> 3 or 4 ?

Personally I prefer (opening Bracket on next line makes nested logic
easy to read):

public class Person
{
   private String name;

   public void setName(String name)
   {
       this.name = name;
   }
}

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA              http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)
IchBin - 04 Jul 2006 17:59 GMT
> Consider the following styles, which one is preferred....
>
[quoted text clipped - 43 lines]
>
> 3 or 4 ?

Personally I prefer (opening Bracket on next line makes nested logic
easy to read):

public class Person
{
    private String name;

    public void setName(String name)
    {
        this.name = name;
    }
}

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA              http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Signature

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA              http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Chris Uppal - 04 Jul 2006 18:52 GMT
> this.name = n;
vs.
> name = n;

I, personally, would prefer to be forced by the compiler to use the first form.
However that isn't how Java works, and there's nothing to be gained by
insisting on that form.  It's probably better /not/ to use it, so that you
don't become dependent on it, and thus have unecessary difficulty reading other
people's code.

The same goes for the static case.

BTW, I agree with IchBin's layout of brackets.

   -- chris
Dale King - 05 Jul 2006 09:03 GMT
>> this.name = n;
> vs.
[quoted text clipped - 5 lines]
> don't become dependent on it, and thus have unecessary difficulty reading other
> people's code.

If you use Eclipse you can have it force you to qualify access to
instance fields. Unfortunately that is an all or nothing thing.

In addition, the CheckStyle style checker has a RequireThis check that
will check for it.

Signature

 Dale King

Hendrik Maryns - 05 Jul 2006 09:13 GMT
Chris Uppal schreef:

>> this.name = n;
> vs.
[quoted text clipped - 3 lines]
> However that isn't how Java works, and there's nothing to be gained by
> insisting on that form.

You can have Eclipse warn you if you don’t.

> BTW, I agree with IchBin's layout of brackets.

I don’t, but that is not important.  IDEs take care of that.  E.g. you
can have two formatting profiles in Eclipse, one of your choice, and one
that fits the team/cooperator/whatever.  Then, if you want to read
someone else’s code, format it with you formatter, then switch to his if
you want to give it back.  For example, I tend to reformat Stefan Ram’s
code, because I find his style unreadable, rational though it might be...

H.
- --
Hendrik Maryns

==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
Ed Kirwan - 05 Jul 2006 09:31 GMT
> -----BEGIN PGP SIGNED MESSAGE-----

>    For example, I tend to reformat Stefan Ram’s
> code, because I find his style unreadable, rational though it might be...

Do you mean Stefan's code snippets that he puts in his posts, or do you
have a link to a grand repository of the good Mister Ram's code?

(I only ask out of curiosity.)

(Which is a truly pointless sentence, now that I think of it.)

(And now that I think of it even more, I'm not sure why I'm not asking
the good Mister Ram himself. Hey, I just work here ...)

Signature

www.EdmundKirwan.com - Home of The Fractal Class Composition.

Download Fractality, free Java code analyzer:
www.EdmundKirwan.com/servlet/fractal/frac-page130.html

Stefan Ram - 05 Jul 2006 09:54 GMT
>Do you mean Stefan's code snippets that he puts in his posts, or do you
>have a link to a grand repository of the good Mister Ram's code?

 I am starting to build a grand repository here:

http://www.purl.org/stefan_ram/pub/ram-jar

 This repository has been reformatted to a more common style
 for the convenience of others, while I internally use my
 personal style.

 In Usenet-Postings I use my personal style, because
 reformatting would be too much effort.

 A rationale for this style:

   Indentation within Braces

     An indentation of just one space often is too small to be
     seen clearly, because the natural width and form of
     characters often varies by an amount that is not very much
     smaller than a space. Therefore, the indentation should
     amount to at least two positions. In order not to waste
     horizontal spaces, an indentation of exactly two positions
     is chosen. This means, that the left position of the next
     level is two larger than the position of the directly
     enclosing level.

     Indentation by two positions within a block

{ ++x;
 ++x; }
^ ^
0 2

     Bad   A small indentation by one position is not always
     visible clearly

{++x;
++x; }

     Good   The indentation by two positions is visible clearly

{ ++x;
 ++x; }

     Bad   A large indentation by more than two positions wastes
     horizontal space with no additional benefit

{    ++x;
    ++x; }

   Spaces within braces

     In mathematics, there are often no spaces at the inner
   side of parentheses or braces in expressions, but spaces
     are used indeed at the inner side of braces in set
     notation, when the braces contain a description (not when
     they contain a list).

     Spaces in set notation

{ x  | x  > 2 }

     This style is adopted here: One space is written at the
     inner side of braces.

     Spaces at the inner side of parentheses within a block

{ ++x; }

     This style is consistent with the indentation by two
     positions, because only using this style, corresponding
     parts of two lines have the same position.

     Bad   No space after the first brace, the two statements are
     misaligned

{++x;
 ++x; }

     Good   One space after the first brace, the two statements
     are properly aligned

{ ++x;
 ++x; }

     Bad   Two spaces after the first brace, the two statements
     are misaligned

{  ++x;
 ++x; }

     There are some exceptions to this rule: No spaces are used
     within empty braces "{}" and between two or more closing
     braces of the same direction "}}", except, when the first
     one of them is part of an empty pair "{} }" (an empty pair
     of braces if treated like a single non-braces character).

   Unified rules for all Brackets

     For simplicity and uniformity, the rules from above apply
     to all kinds of brackets, including parentheses, braces
     (curly brackets), square brackets, and angle brackets.

     Spaces within parentheses and square brackets

{ y = f( x )+ g() + a[ 2 ]; }

     Binary operators are surrounded by a space, but the space
     is omitted, when there already is a space on the other
     side of a sequence of bracket directly beside the
     operator: By this rule " )+" is written instead of " ) +".

   Representation of the Syntactical Structure

     A method declaration in Java consists of a head and a
     body. The following representation shows this structure:

     Good formatting according to the structure

void alpha() // head
{ beta(); }  // body

     The following formatting is misleading, because the line
     break does not match the structural break:

     Bad   line break within the body

void alpha() { // head and the beginning of the body
 beta(); }  // the rest of the body

     This formatting also would make no sense for blocks within
     blocks. So it is often not used for such blocks. Therefore
     even the adopters of this style can not use it uniformly.

   Left Braces Look Like "bullets"

     There is a well known style to publish lists in typography
     using bullets sticking out on the left, looking like this:

     Common list representation with bullets in typography

o This is the first point
 of this list, it is written
 here just as an example.

o Here is another entry

o This is another example given
 just as an example to show
 an example

     The braces of the beginnings of blocks stand out on the
     left just the same, when the formatting being described
     here is used, so they look quite naturally as
     beginning-of-a-block markers, when one is used to the
     typographical list notation:

     Left braces look like bullets to mark blocks

{ printf(); printf();
 printf(); printf(); printf();
 printf(); printf();   }

{ printf(); printf(); }

{ printf(); printf(); printf();
 printf(); printf();
 printf(); }

   Neutrality

     Someone wrote this C code:

     Code someone wrote

while( fgets( eingabe, sizeof eingabe, stdin ))
 if( sscanf( eingabe, "%d", &wert )!= 1 )
   fprintf( stderr, "Please enter a number!\n" );
 else
   summe += wert;

     It amazes me that I can add braces by my style conventions
     without the need to change the position of any character
     of the given code:

     The code from above plus braces

while( fgets( eingabe, sizeof eingabe, stdin ))
{ if( sscanf( eingabe, "%d", &wert )!= 1 )
 { fprintf( stderr, "Please enter a number!\n" ); }
 else
 { summe += wert; }}
Ed Kirwan - 05 Jul 2006 12:00 GMT
>   I am starting to build a grand repository here:
>
> http://www.purl.org/stefan_ram/pub/ram-jar

Nice (I didn't know JavaDocs could reference source code) and laudable;
and I know you have a note about a certain lack of documentation, but
can't you write up something just to tie it all together? You mention
that it's, "a library for Java 1.6;" but a library that does what?

Signature

www.EdmundKirwan.com - Home of The Fractal Class Composition.

Download Fractality, free Java code analyzer:
www.EdmundKirwan.com/servlet/fractal/frac-page130.html

Stefan Ram - 05 Jul 2006 17:15 GMT
>> http://www.purl.org/stefan_ram/pub/ram-jar
>Nice (I didn't know JavaDocs could reference source code) and laudable;
>and I know you have a note about a certain lack of documentation, but
>can't you write up something just to tie it all together? You mention
>that it's, "a library for Java 1.6;" but a library that does what?

 This library has no cohesion. (Insofar it can be compared to a
 general collection with several packages, such as rt.jar or
 Jakarta Commons.) A description of its features, as you
 suggest, indeed is on my todo list.
Thomas Hawtin - 04 Jul 2006 19:25 GMT
> Consider the following styles, which one is preferred....

The convention is:

public class Person {

   private String name;

   public void setName(String name) {
       this.name = name;
   }
}

No point making up new names to represent the same concept.

Or even better:

public final class Person {

   private final String name;

   public Person(String name) {
       this.name = name;
   }
}

> and...if in case of static ....
>
[quoted text clipped - 7 lines]
>     }
> }

The problem here is that you have a non-final static, which is almost
certainly a mistake.

In the case of static finals, you cannot qualify with the class name
(which can be a bit of a pain in static initialisers).

Tom Hawtin
Signature

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

Mark Space - 04 Jul 2006 19:33 GMT
>> Consider the following styles, which one is preferred....
>
[quoted text clipped - 41 lines]
>
> Tom Hawtin

Huh, why do you say that?  Do you mean in this specific example (which I
might be inclined to agree)?  Or do you mean in general (which I might
be inclined to disagree)?

I don't see anything in class variables in general that makes them
"almost certainly a mistake," but maybe there is something I'm missing.
Class variables are a good and useful concept, and I don't see anything
wrong with using them.
Thomas Hawtin - 04 Jul 2006 20:21 GMT
>> The problem here is that you have a non-final static, which is almost
>> certainly a mistake.
>>
>> In the case of static finals, you cannot qualify with the class name
>> (which can be a bit of a pain in static initialisers).

> Huh, why do you say that?  Do you mean in this specific example (which I
> might be inclined to agree)?  Or do you mean in general (which I might
> be inclined to disagree)?

I mean mutable statics in general are bad.

You are making an assumption about the system in a single class. Ever
tried handling an applet (or servlet) with static variables? Nightmare.

Tom Hawtin
Signature

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

Mark Space - 04 Jul 2006 20:54 GMT
>> Huh, why do you say that?  Do you mean in this specific example (which I
>> might be inclined to agree)?  Or do you mean in general (which I might
[quoted text clipped - 4 lines]
> You are making an assumption about the system in a single class. Ever
> tried handling an applet (or servlet) with static variables? Nightmare.

Hmm, well, I've never done any work with applets, so I'll reserve
judgment.  It sounds to me like maybe class variables were used where
the should not have been, but I don't know the full story.
Thomas Hawtin - 04 Jul 2006 21:22 GMT
> Hmm, well, I've never done any work with applets, so I'll reserve
> judgment.  It sounds to me like maybe class variables were used where
> the should not have been, but I don't know the full story.

They pretty much shouldn't be used anywhere. Loggers and weak caches are
the only counter examples that springs to mind.

Tom Hawtin
Signature

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

Jeffrey Schwab - 04 Jul 2006 22:11 GMT
>> Hmm, well, I've never done any work with applets, so I'll reserve
>> judgment.  It sounds to me like maybe class variables were used where
>> the should not have been, but I don't know the full story.
>
> They pretty much shouldn't be used anywhere. Loggers and weak caches are
> the only counter examples that springs to mind.

A mutable, static integer to keep track of how many times a class has
been instantiated might be a "counter example," if you'll pardon the pun.
Thomas Hawtin - 04 Jul 2006 23:20 GMT
> A mutable, static integer to keep track of how many times a class has
> been instantiated might be a "counter example," if you'll pardon the pun.

What use is that, other than debugging? (Actually you would probably be
better off with a static final AtomicInteger. Come to think of it, that
is used by ThreadLocal in preference to Object.hashCode.)

Tom Hawtin
Signature

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

Jeffrey Schwab - 05 Jul 2006 02:17 GMT
>> A mutable, static integer to keep track of how many times a class has
>> been instantiated might be a "counter example," if you'll pardon the pun.
>
> What use is that, other than debugging? (Actually you would probably be
> better off with a static final AtomicInteger. Come to think of it, that
> is used by ThreadLocal in preference to Object.hashCode.)

It's the first example I ever saw of a mutable static field, and it
allowed me to make a pun.

I've used something similar in production code to help tune memory
allocation.  I had a factory that created objects of various types.
Client code could release objects that were no longer needed, and the
factory could cache a finite number of the released objects for later
use, to satisfy further allocation requests quickly.  In order to cache
the objects most likely to be requested in the future, the factory kept
counts of how many objects of each type had been allocated recently.
The factory was only intended for use from a single thread, so there was
no need for atomic counters.

You're absolutely right that this kind of counter should be a
per-instance member of a factory class, but the factory was a singleton
(specifically to maximize the effectiveness of the cache).  Because it
was a singleton, I just made all its member methods static, and
correspondingly all its fields.  If I had it to do over, I probably
would use a different approach.
Mark Space - 05 Jul 2006 00:30 GMT
>> Hmm, well, I've never done any work with applets, so I'll reserve
>> judgment.  It sounds to me like maybe class variables were used where
[quoted text clipped - 4 lines]
>
> Tom Hawtin

So, singletons and monostate are bad design then?

http://www.objectmentor.com/resources/Farticles/SingletonAndMonostate.pdf

How about a Reader-Writer object?

http://www-dept.cs.ucl.ac.uk/staff/W.Emmerich/lectures/C340-97-98/conc13.pdf

I could go on.  I think I understand what you are trying to say.  Many
people may over-use class variables, or use them incorrectly or without
considering multi-threading issues.  But class variables themselves are
not bad at all, in fact they are very useful.  They are an important
part of the language, and they should not be eschewed where they are the
correct solution.
Thomas Hawtin - 05 Jul 2006 12:45 GMT
>> They pretty much shouldn't be used anywhere. Loggers and weak caches are
>> the only counter examples that springs to mind.
[quoted text clipped - 4 lines]
>
> http://www.objectmentor.com/resources/Farticles/SingletonAndMonostate.pdf

Too bloody right. For the most part they are used as global variables.

> How about a Reader-Writer object?
>
> http://www-dept.cs.ucl.ac.uk/staff/W.Emmerich/lectures/C340-97-98/conc13.pdf

Huh? I really don't get the relevance.

Tom Hawtin
Signature

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

Stefan Ram - 04 Jul 2006 19:34 GMT
>Or even better:
>    public Person(String name) {

 Does a person become a new person, when it changes its name?
Thomas Hawtin - 04 Jul 2006 20:24 GMT
>> Or even better:
>>    public Person(String name) {
>
>   Does a person become a new person, when it changes its name?

It's better that than changing his or her name without telling anyone...

Tom Hawtin
Signature

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

Patricia Shanahan - 04 Jul 2006 21:32 GMT
> Consider the following styles, which one is preferred....
>
[quoted text clipped - 17 lines]
>     }
> }

I don't like either of those, because they use a meaningless identifier
for the parameter, where it will be visible in e.g. Javadocs. This is a
public method in a public class, so the choice of identifiers is really
important.

My first choice, when a field and parameter have the same meaning, is to
pick the best identifier I can think of for that meaning and use it for
both:

public void setName(String name) {
 this.name = name;
}

Patricia


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.