Stylistic note on loops

S

Stefan Ram

Arne Vajhøj said:
<quote>
Braces are used around all statements, even single statements, when they
are part of a control structure, such as a if-else or for statement.
This makes it easier to add statements without accidentally introducing
bugs due to forgetting to add braces.
</quote>

This quote, however, does not apply to »{}«: »{}« are not
»braces used around a statement«, because »« is not a statement.
 
A

Arne Vajhøj

admittedly, Java is not one of my most heavily used languages (much more of
my development is in C and C++, and of this, a much larger portion is in C).

it is possible that some amount of C-like stylistic preferences bleed over.

Java and C/C++ coding conventions differ a lot more than
the basic syntax.

admittedly, there is a notion I have heard before, that when a person moves
from one language to another, their style should also entirely change as
well to be whatever is most accepted by the particular
language/community/... personally, I find this idea both inconvinient and
unecessary, given that these languages retain mostly similar syntax (and
what works aesthetically in one language should work similarly well in the
others, and if there is a severe conflict then this would imply that maybe
something is not right).

It is not easy but one should do it.

It will be very confusing for a maintenance programmer working
on code in language X without knowing language Y, if the code
uses the coding conventions of Y.
actually, I have seen cases where people have gone around and changed all
the capitalization or indentation or whatever else in an existing codebase,
and IMO this is ugly and inconvinient, as then often pieces of older code
will no longer work simply because the capitalization is different (and then
one has to stub things or modify the code or similar to make it fit again).

An IDE with refactoring capability can do that safely.

But I admit that the source control statistics will go
completely crazy.

Arne
 
A

Arne Vajhøj

This quote, however, does not apply to »{}«: »{}« are not
»braces used around a statement«, because »« is not a statement.

I was commenting on whether it should be used for "single statement"
(which occurred in what I quoted).

I think the logic applies to no statement as well, but strictly speaking
the quote does not cover that.

Arne
 
A

Arne Vajhøj

In fact, nearly everything could be a typo in source code.


Usually, I assume that the programmer intented what he wrote,
unless I have a reason to assume otherwise. Such a semicolon »;«
is not such a reason. An »{ /* EMPTY */ }« makes me feel
somewhat annoyed/offended.

NB: THE PERIOD AT THE END OF THE PREVIOUS SENTENCE WAS
WRITTEN INTENTIONALLY TO MARK THE END OF THE SENTENCE.
SEE: http://en.wikipedia.org/wiki/Full_stop

The cost of the ending period being removed is approx. zero
while the cost of the semicolon in the code could be pretty
big, so I am not sure that it makes sense to conclude
from English to code.

Arne
 
A

Arne Vajhøj

It reminds me of suggestions to write

Character.isLetter( s.charAt( i ))== true

, because this is »more readable« than

Character.isLetter( s.charAt( i ))

. It might be more readable for persons who know English,
but no or little Java. But source code becomes less readable
for experienced programmers when it is written with such a
reader in mind.

One has to stop somewhere and make some minimum assumptions
about the maintenance programmers skills.

Assuming that they know how boolean expressions work
is IMHO an OK assumption. Every developer no matter
level and language experience should know that.

Arne
 
E

Eric Sosman

[...]
int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{
/* EMPTY */
}

Another idiom you may encounter for empty loop bodies is

for (i = 1; Character.isLetter(s.charAt(i)); i++)
continue;

.... with or without curly braces, according to local style.
 
E

Eric Sosman

[...]
In C, to skip two space-separated integral numerals
(under certain circumstances):

while( isnum( *++c )); while( isspace( *++c )); while( isnum( *++c ));

, this is obvious and intelligible. [...]

... and wrong, unless the "certain circumstances" happen to
include foreknowledge that the string is exactly of the given form,
and not, for example, "a23z" (which would cause the third loop to
wander drunkenly past the end of the string, inspecting whatever
random bytes it happened to find in the rest of memory).

Personally, I cannot recall a single occasion in more than forty
years of programming when I (1) wanted to skip over two numbers this
way and (2) wanted to ignore what those numbers were and (3) had such
complete trust that no oddly-formatted strings could ever show up.
(I've had (1) and (2) together, but not along with (3); (3) almost
never holds.) That is, I have never had the slightest urge to write
three such loops, do not expect that I ever will, and do not intend
to let them influence my style. YMMV, but I hope sincerely that it
doesn't V appreciably.
 
C

ClassCastException

I frequently use a for loop to empty a table something like: for
(;table.getRowCount() > 0;table.removeRow(0)); notice, you don't even
need the body {}, if your body is empty or one line, you can use just a
; to end.

Eeeuw. This is exactly the type of loop (loop until something changes
state) that should almost always be a while:

while (table.getRowCount() > 0) {
table.removeRow(0);
}
 
B

BGB / cr88192

Arne Vajhøj said:
Java and C/C++ coding conventions differ a lot more than
the basic syntax.

but, in many respects the basic syntax is similar between these languages,
and WRT things like use of braces, indentation, ... there really does not
need to be much difference.

It is not easy but one should do it.

It will be very confusing for a maintenance programmer working
on code in language X without knowing language Y, if the code
uses the coding conventions of Y.

except, Java and C/C++ syntax, and common stylistic conventions, are close
enough that, in many regards, the differences are neglibible...

granted, one can't do C style string or pointer funkiness in Java, but even
in C these are things to be used with care, as overusing them can make code
ugly.

some many common C-style naming conventions would be rather out of place in
Java, but they are unneeded anyways since the language has things like
packages and classes (and doesn't allow top-level variables and functions),
naturally leading to some differences in naming and organization.


most of the rest are matters that people will debate endlessly with no real
consensus.

An IDE with refactoring capability can do that safely.

But I admit that the source control statistics will go
completely crazy.

it is a mess when the project is being worked on by multiple independent
parties, and someone maintaining their own code has their code break because
someone working on the main project (or someone on a different team, or
whatever, ...) decided to change a bunch of stuff.


admittedly, this is a reason I am a bit fussy about wanting projects
partitioned between individuals and groups:
it generally reduces the problem of people stepping on each other while
working on the code, and also the matter of someone random thinking they
know how the code should be better than the main people maintaining it, as
well as for reducing the politics and beuracracy related to updates. since
if each person "owns" their own little section of code, there doesn't need
to be some much debate about localized changes, and instead people can
debate about what happens at the borders (as the interfaces become implicit
contracts).

or such...
 
B

BGB / cr88192

Arne Vajhøj said:
No. In Java we typical use them even for single statements.

odd...



No. Reading code that uses different styles or very unusual
styles make reading code slower.

Slower = cost more $$$$ for maintenance.

$$$$ is relevant in professional software development.

only if one can seriously show that most people are actually effected, in
general, by getting confused over matters of braces and whitespace.

apart from a few edge cases:
the big ugly block of characters;
the ugly 1 or 2-space tab (luckily, this one has largely died off, as the 4
or 8 space tab are near-universal);
....

it would be a surprise if people were really effected much.

Even MS has given up on that.

if one looks in 'windows.h' and similar, they see it all over the place, as
well as all-caps type-names...

granted, it would be ill advised to write new code like this, as it is bad
enough dealing with this in Windows code, but even then, it still serves a
purpose:
"warning: this region of code is almost completely non-portable...".

Wrong.

It would absolutely terrible if every generation of developers had
to learn everything from scratch instead of benefiting from
best practices learned by previous generations of developers.

people do so already...

"doing what makes sense" is, maybe 75%-90% of the time or more, following
whatever is the common practice in a particular case...

then a person does something different when there is some good reason to do
so, rather than adhering to dogmas even in cases where it would make the
code worse as a result.

"making sense" is, after all, primarily a matter of localized cost
minimization, and if following conventions makes sense, then this is what
makes sense, and if a convention is stupid, it may make sense to blow it
off...
 
B

BGB / cr88192

Eric Sosman said:
[...]
In C, to skip two space-separated integral numerals
(under certain circumstances):

while( isnum( *++c )); while( isspace( *++c )); while( isnum( *++c ));

, this is obvious and intelligible. [...]

... and wrong, unless the "certain circumstances" happen to
include foreknowledge that the string is exactly of the given form,
and not, for example, "a23z" (which would cause the third loop to
wander drunkenly past the end of the string, inspecting whatever
random bytes it happened to find in the rest of memory).

Personally, I cannot recall a single occasion in more than forty
years of programming when I (1) wanted to skip over two numbers this
way and (2) wanted to ignore what those numbers were and (3) had such
complete trust that no oddly-formatted strings could ever show up.
(I've had (1) and (2) together, but not along with (3); (3) almost
never holds.) That is, I have never had the slightest urge to write
three such loops, do not expect that I ever will, and do not intend
to let them influence my style. YMMV, but I hope sincerely that it
doesn't V appreciably.

I have... rarely... used code similar to the example, but usually this is
for special case logic (typically pattern matching), where a variation from
the accepted form is usually regarded as a match failure (some extra checks
are then added to verify at each spot that the characters are what are
expected, and deviation results in giving up).


othertimes though, I have used string-based logic to drive special purpose
finite-state-machines, but an invalid string here is a potentially serious
condition (these are places where a malformed string either means something
has gone notably wrong, or this compromises the internal integrity of the
code).

usually this kind of thing is mostly confined to things like code-generation
and compilation logic, or for things operating in close proximity to the
native calling convention, and in a few cases for self-composing or
self-modifying code.

both my x86-assembler and x86-interpreter use some logic similar to the
above as well (as a control notation for emitting and decoding machine
instructions), where in this case the idea was partly motivated by something
I saw in the Quake3 JIT engine.


but, for most general-purpose code, this sort of thing is nasty.

for general-purpose strings, I prefer to regard them as immutable atomic
units.
 
E

Eric Sosman

Eeeuw. This is exactly the type of loop (loop until something changes
state) that should almost always be a while:

while (table.getRowCount()> 0) {
table.removeRow(0);
}

Side-note and topic drift: That's an O(N^2) loop if `table' is
backed by something like an ArrayList, where all the undeleted rows
need to be slid downward to fill the vacated space. We don't *know*
what's behind `table' in this fragment, of course, but given our
ignorance it might be prudent to write

while (table.getRowCount() > 0) {
table.removeRow(table.getRowCount() - 1);
}

Still better,

while (! table.isEmpty()) {
table.removeRow(table.getRowCount() - 1);
}

Best of all,

table.clear();

We now return you to your regularly scheduled style war.
 
B

BGB / cr88192

Arne Vajhøj said:
The cost of the ending period being removed is approx. zero
while the cost of the semicolon in the code could be pretty
big, so I am not sure that it makes sense to conclude
from English to code.

one would have to question the competence of the programmers to make this
case.

it becomes a matter of habit when and where to place them, and things are
not exactly looking good for the project if the programmers are not skilled
enough to deal with these sort of issues.

so help you if anything actually difficult pops up...
 
M

markspace

but, in many respects the basic syntax is similar between these languages,
and WRT things like use of braces, indentation, ... there really does not
need to be much difference.


You probably already know this but Sun (now Oracle) publishes guidelines
for Java code styles. And pretty much everyone follows them. While not
enforced by the compiler to the extend that say Python does, they are
still the de facto standard in the Java programming world.

Specifically WRT braces, Sun recommends that you always use braces, even
for blocks that are a single statement and could use a semi-colon
instead. So for an empty statement, I used braces.
 
S

Stefan Ram

Arne Vajhøj said:
The cost of the ending period being removed is approx. zero

Somewhat off topic here, but:

»Karl Kraus was convinced that every little error, albeit
of an importance that was seemingly limited in time and
space, shows the great evils of the world and era. Thus,
he could see in a missing comma a symptom of that state
of the world that would allow a world war. One of the
main points of his writings was to show the great evils
inherent in such seemingly small errors.

Language was to him the most important tell-tale for the
wrongs of the world. He viewed his contemporaries'
careless treatment of language as a sign for their
careless treatment of the world as a whole.«

http://en.wikipedia.org/w/index.php?title=Karl_Kraus&oldid=384906924

Karl Kraus died in 1936 and didn't know programming
languages, but compare the above with:

»I have never, ever, ever seen a great software developer
who does not have amazing attention to detail.«

http://www.softwarebyrob.com/articles/Personality_Traits_of_the_Best_Software_Developers.aspx
 
M

markspace



Yeah, but the de facto standard. Someone already linked to the Java
code style guidelines, so I won't repeat it here.

only if one can seriously show that most people are actually effected, in
general, by getting confused over matters of braces and whitespace.


I think they are affected. I'm not affected by the code I wrote, but I
assume a maintainer would be. Therefore I asked for opinions in a
public forum.

apart from a few edge cases:
the big ugly block of characters;
the ugly 1 or 2-space tab (luckily, this one has largely died off, as the 4
or 8 space tab are near-universal);


In my experience, tabs died out a decade ago. All indentation is with
spaces now. I always favored tabs myself, but the world has moved on.
Que sera sera.

if one looks in 'windows.h' and similar, they see it all over the place, as
well as all-caps type-names...


Well, yeah. They have to be backwards compatible. They can't change
*existing* public APIs.


Trying to say this with good humor: I get the feeling that some of your
info is 15 years out of date. ;)
 
M

markspace

You'd better hope that such a non-letter character exists, or
you'll march right off the end of the string ...


Yes. :) As has been pointed out repeatedly. :) :) I think it is
guaranteed, but you and everyone else was quite correct to point this
out. I'd better add a check in anyway, I do so dislike getting
IndexOutOfBoundException from "working" programs.
 
A

Arne Vajhøj

but, in many respects the basic syntax is similar between these languages,
and WRT things like use of braces, indentation, ... there really does not
need to be much difference.

True. There rare no need for a difference.

But there are a difference.
except, Java and C/C++ syntax, and common stylistic conventions, are close
enough that, in many regards, the differences are neglibible...

That would result in horrible code.

The basic syntax is very similar. But standard style are very
different. Common paradigms are different. Etc..
most of the rest are matters that people will debate endlessly with no real
consensus.

No.

There are about 99% concensus or so that it is good to follow coding
conventions.
it is a mess when the project is being worked on by multiple independent
parties, and someone maintaining their own code has their code break because
someone working on the main project (or someone on a different team, or
whatever, ...) decided to change a bunch of stuff.

It is always a mess to change public API's.

But if someone was sleeping while reviewing the API and
approved something completely non standard, then they
pay the price later.

Arne
 
B

BGB / cr88192

markspace said:
You probably already know this but Sun (now Oracle) publishes guidelines
for Java code styles. And pretty much everyone follows them. While not
enforced by the compiler to the extend that say Python does, they are
still the de facto standard in the Java programming world.

Specifically WRT braces, Sun recommends that you always use braces, even
for blocks that are a single statement and could use a semi-colon instead.
So for an empty statement, I used braces.

probably, but OTOH, MS has different guidelines for C#, and C and C++ tend
to use slightly other conventions as well...


in all cases though, most of these conventions are immaterial.

the compiler doesn't care, and there is little reason people should care
either, since a human is smarter and more flexible than a compiler, people
should presumably act as such...

what weight do they hold, as they are basically just statements of
preferences by some party, rather than being based strictly on what is most
practical or convinient, or being imposed by a limitation of the technology,
or similar...

it is really no different than saying that one can't stir drinks with a
screwdriver:
little exists in either the drink or the screwdriver to prevent this, and
either way the drink gets stirred.
the only real difference then is that one has not had to go and fetch a
spoon, and created a piece of dirty silverware, ... (since a screwdriver can
just be wiped off...).

or such...
 
M

markspace

probably, but OTOH, MS has different guidelines for C#, and C and C++ tend
to use slightly other conventions as well...


And MS meas what to C or C++? They implement a compiler, they don't
issue the standard. If IEEE or ANSI published standards for C coding,
I'd say we should follow them. It happens that they don't (AFAIK), so
coding standards tend to be wild west style.

(Actually I think there are some implicit code style standards in K&R,
but that's not quite official, so...).

Sun is... what, the copyright holder of the Java spec? And they own
several critical patents, apparently. Modifying the JLS is a public
process, because Sun wants Java to be widely supported and used, but it
Java is their property. They issue guidelines, the world follows those
guidelines. When folks who are new here post code with underbars in
variable names (for example), it's always jarring and they always get
corrected.

WRT C#, MS owns their baby and they can issue what guidelines they like.
In that case I think we should follow them.

in all cases though, most of these conventions are immaterial.


This is where we disagree. I think it's a big advantage for everyone to
use the same coding standard. All the code in Java that I see, whether
my own, Sun's, Apache, etc. uses the same standard, and it makes it very
easy to read. That's a real cost driver there, imo, and every good
professional should strive to drive done costs where practical.
 

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

Similar Threads


Members online

Forum statistics

Threads
474,264
Messages
2,571,066
Members
48,770
Latest member
ElysaD

Latest Threads

Top