Style of coding

T

Thomas Hawtin

Mark said:
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
 
P

Patricia Shanahan

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;
}
}

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
 
J

Jeffrey Schwab

Thomas said:
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.
 
B

Bent C Dalager

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.

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
 
S

Stefan Ram

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 ){} }
 
S

Stefan Ram

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 ){} }
 
T

Thomas Hawtin

Jeffrey said:
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
 
M

Mike Schilling

Chris Uppal said:
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...

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.
 
S

Stefan Ram

Mike Schilling said:
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;
}

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.
 
A

AndrewMackDonna

Mike said:
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.

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.
 
M

Mark Space

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

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.
 
J

Jeffrey Schwab

Thomas said:
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.
 
M

Mike Schilling

Stefan Ram said:
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.

:)

When actually coding, I take more care than when dashing off a Usenet
posting, of course.
 
D

Dale King

Stefan Ram 寫é“:


hi again :)

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.
 
D

Dale King

Chris said:
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.

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.
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Chris Uppal schreef:
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.

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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEq3Sye+7xMGD3itQRAqVVAJ0RWt0Lo+d0DtD1qy4Bf0wz190ovACdFnoz
BX2z69h2jjEPRMUTuKdPv9g=
=N3+z
-----END PGP SIGNATURE-----
 
E

Ed Kirwan

Hendrik said:
-----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 ...)
 
S

Stefan Ram

Ed Kirwan said:
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; }}
 
E

Ed Kirwan

Stefan said:
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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top