Java Forum / General / September 2007
Coding Standards
davidsamith@gmail.com - 31 Aug 2007 07:05 GMT 'Good code' is code that works, is bug free, and is readable and maintainable. Standards need to be followed for coding. Read more...
http://brsx.co.uk/SWtesting/FAQs/FAQs012.asp
Karl Uppiano - 31 Aug 2007 08:51 GMT > 'Good code' is code that works, is bug free, and is readable and > maintainable. Standards need to be followed for coding. Read more... > > http://brsx.co.uk/SWtesting/FAQs/FAQs012.asp He goes on to write
"...but everyone has different ideas about what's best, or what is too many or too few rules."
and therein lies the problem.
For example, my code tends to be completely devoid of comments (because I find them distracting interspersed with the code -- the code itself should be expressive enough without all that chatter) -- except for JavaDocs, which I write copiously. It gives me a nice place to describe the class, member variable, or method, with the input parameters, return values and exceptions thrown, in a way that is far more structured than you would get with ad-hoc comments. In fact, if I find myself writing a comment inline with the code (often justifying something that is just "too cool"), it is usually an indication that my implementation is flawed.
I tend to keep my methods rather short (less than a screenful). It makes it easier to document and understand what is going on, and helps to modularize the operations. That is just my style developed over 25 years of programming professionally. I developed a "JavaDoc" style of commenting my code when I was developing in C. I don't expect everyone to follow my style.
As for whitespace and bracket alignment, I often thought that repositories should delete all extra whitespace, and editors should expand it back according to individual developer preferences. That hasn't happened yet.
Bent C Dalager - 31 Aug 2007 10:15 GMT >As for whitespace and bracket alignment, I often thought that repositories >should delete all extra whitespace, and editors should expand it back >according to individual developer preferences. That hasn't happened yet. This would clash with the "artistic vertical alignment" crowd who like to put in some extra effort to vertically align things that somehow belong together in order to make it more readable. This sort of alignment is notoriously difficult to do automatically (ultimately, it can't really be done since it depends on rather delicate aesthetic judgements) and so killing whitespace would not be a reversible process.
Cheers Bent D
 Signature Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd powered by emacs
Karl Uppiano - 02 Sep 2007 00:49 GMT >>As for whitespace and bracket alignment, I often thought that repositories >>should delete all extra whitespace, and editors should expand it back [quoted text clipped - 7 lines] > judgements) and so killing whitespace would not be a reversible > process. Yeah, I thought about that. It isn't a fully formed idea. I think you could make compression rules and expansion rules that could take tabs, stand alone newlines, etc., into consideration. Perhaps I should start a software company... ;-)
Mike Schilling - 02 Sep 2007 01:57 GMT >>> As for whitespace and bracket alignment, I often thought that >>> repositories should delete all extra whitespace, and editors should [quoted text clipped - 13 lines] > tabs, stand alone newlines, etc., into consideration. Perhaps I > should start a software company... ;-) I think you'd want to go further. Define an object model for a Java source file, and have an engine that renders the object graph according to the user's preferences. This would make it impossible to save an incorrectly formed Java file (it wouldn't have to compile, but it would have to follow at least some of the syntactical rules), or perhaps anything ungrammatical would be saved as text.
Arne Vajhøj - 02 Sep 2007 02:23 GMT >>>> As for whitespace and bracket alignment, I often thought that >>>> repositories should delete all extra whitespace, and editors should [quoted text clipped - 18 lines] > at least some of the syntactical rules), or perhaps anything ungrammatical > would be saved as text. Sounds a bit like IBM VAJ.
I would not consider that way a success.
Arne
Mike Schilling - 02 Sep 2007 07:29 GMT >> I think you'd want to go further. Define an object model for a Java >> source file, and have an engine that renders the object graph [quoted text clipped - 5 lines] > > Sounds a bit like IBM VAJ. That made the mistake of trying to model a Java class instead of a Java source file.
Matthias Buelow - 31 Aug 2007 15:33 GMT > For example, my code tends to be completely devoid of comments (because I > find them distracting interspersed with the code -- the code itself should > be expressive enough without all that chatter) Then you apparently have never implemented any more complicated or non-intuitive algorithm...
> -- except for JavaDocs, which > I write copiously. It gives me a nice place to describe the class, member > variable, or method, with the input parameters, return values and exceptions > thrown, in a way that is far more structured than you would get with ad-hoc > comments. Which are exactly the kind of useless comments that clatter source code. I thought the code should be expressive enough without all that chatter? Documenting trivial details is nonsense. You should explain the big picture in comments and why you did some details the way you did them, and not verbosely reformulate parts of the source code.
Unfortunately, your approach is typical for many Java (or industrial, for that matter) programmers.
I've seen quite some programs where the programmer said "don't have to explain the stuff, the source code is obvious", which were basically unmaintainable.
Lew - 31 Aug 2007 15:45 GMT Karl Uppiano wrote:
>> -- except for JavaDocs, which >> I write copiously. It gives me a nice place to describe the class, member >> variable, or method, with the input parameters, return values and exceptions >> thrown, in a way that is far more structured than you would get with ad-hoc >> comments.
> Which are exactly the kind of useless comments that clatter source code. > I thought the code should be expressive enough without all that chatter? > Documenting trivial details is nonsense. You should explain the big > picture in comments and why you did some details the way you did them, > and not verbosely reformulate parts of the source code. While I agree with Matthias's points about commenting the more obscure parts of one's code, I cannot believe that he seriously is against the use of Javadocs. Javadocs are critical in Java source. They serve double duty - not only do they help future users of a class to use it correctly, they cover most of the non-trivial comments one would make about a class or method (or other exposed member). It's hardly "chatter".
 Signature Lew
Martin Gregorie - 31 Aug 2007 17:57 GMT > Karl Uppiano wrote: >>> -- except for JavaDocs, which I write copiously. It gives me a nice [quoted text clipped - 14 lines] > correctly, they cover most of the non-trivial comments one would make > about a class or method (or other exposed member). It's hardly "chatter". I've been experimenting with writing class specifications as ASCII text files structured as:
Introductory text describing the class and its intended purpose, limitations, etc.
repeat for all constructors Constructor description constructor header end-repeat
repeat for all public or protected methods Method description method header end-repeat
so that, once I'm happy that the spec is complete, correct, spell-checked and readable it can be turned into self-documented compilable code by adding:
- the class header and block - turning descriptions into Javadoc comments and inserting HTML formatting tags etc - adding minimal blocks behind the constructor and method headers.
Once this has been done its easy to add implementing code and private methods.
So far its worked out pretty well, resulting in Javadoc output that reads nicely and manages to avoid the creation of separate documentation that must be maintained (but never is).
I agree with Lew about commenting the code: if a method is just inline statements then the method description is all that's needed, but more complex code can benefit from having descriptive comments dropped into it. These are always indented to match the code and use /* ... */ delimiters (never /**) because I don't think that this type of comment has any place in the Javadoc method description.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Ed Kirwan - 31 Aug 2007 19:55 GMT ...
> I agree with Lew about commenting the code: if a method is just inline > statements then the method description is all that's needed, ...
I'm sorry for being a bit dim, Martin, but it's been a long day and it's now 7-minutes-to-beer-o'clock: what do you mean by, "Inline," here?
 Signature .ed
www.EdmundKirwan.com - Home of The Fractal Class Composition
Martin Gregorie - 01 Sep 2007 13:54 GMT > I'm sorry for being a bit dim, Martin, but it's been a long day and it's now > 7-minutes-to-beer-o'clock: what do you mean by, "Inline," here? Comments placed ahead of the statements they describe and indented to the same level as the statements, e.g.
/** * Method description. */ public void method() { statement; statement;
/* A comment about the next few statements */ statement; statement; if (blahblah) { /* A comment about this branch */ statement; .... } }
and so on. Before anybody jumps in, yes I'm with Lew on the indenting convention: I find
header { ..... }
much easier to read than
header { ..... }
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Joshua Cranmer - 01 Sep 2007 14:37 GMT > and so on. Before anybody jumps in, yes I'm with Lew on the indenting > convention: I find [quoted text clipped - 9 lines] > ..... > } But that means you have to do this:
if { ... } else { ... }
It was those if/else statements that convinced me to switch to brackets on the same line.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Patrick May - 01 Sep 2007 15:39 GMT >> and so on. Before anybody jumps in, yes I'm with Lew on the >> indenting convention: I find [quoted text clipped - 23 lines] > It was those if/else statements that convinced me to switch to > brackets on the same line. That's why I prefer the old Whitesmith format:
if (foo) { . . . } else { . . . }
Lining the braces up with the block they delimit seems logical. I also don't put braces around single statements -- I've never had a bug related to that because Emacs indents everything appropriately for me.
Incidentally, I've heard several times of a study done by NASA that demonstrated a statistically significant lower defect rate in code that formatted with braces on their own lines than in code that uses the K & R style. I'd like to see that study, if it's not an urban legend from the style wars.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | Large scale, mission-critical, distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, middleware, SOA)
Martin Gregorie - 01 Sep 2007 15:40 GMT >> and so on. Before anybody jumps in, yes I'm with Lew on the indenting >> convention: I find [quoted text clipped - 23 lines] > It was those if/else statements that convinced me to switch to brackets > on the same line. Sure, but its only two lines more than
if (a) { blah; ..... } else { blather; ...... }
and that's more difficult to read when you're looking for bracket mismatches. At least it is for me, but ymmv.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Stefan Ram - 01 Sep 2007 16:30 GMT >Sure, but its only two lines more than > if (a) { For completeness, my style:
I write short if-statements on a single line, preferably without unnecessary braces:
if( a )b();
This might be influenced by my general style rule:
»When two notations have the same meaning, in doubt, choose the one that is shorter.«
Line breaks are added so as to respect the syntactical structure. The if-statement's syntax is:
»if ( Expression ) Statement«
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.9
The following line break would not respect this:
.----------- break between »if ( Expression )« and »Statement« v if( a ) { ^ '--------- line break b(); ...
This disrespects »well-structured programming« according to my definition of that term:
»A formal text is well-structured if its surface structure matches its deep structure as close as possible.«
Above, the surface structure (line breaks) is misleading about the deep structure (syntactical breaks).
Therefore, it looks ugly to me, and I break like:
if( a ) // if ( Expression ) { b(); } // Statement
When there are multiple lines in the block:
if( a ) { b(); c(); }
Sometimes, I want to put the braces on a line for themselves to add additional vertical space for readability. If I have to force each braces on a line, I write:
if( a ) { b(); c(); }
Here, one sees, that I do not align matching braces.
I feel the first brace »{« to be still part of the outer block, because it transfers the control to the inner block like a method call, which is still part of the calling block.
Conversely, the last brace »}« transfers control back to the caller, like a return statement. So it is indented with the inner block.
This is also consistent with a one-pass indenter, that can change indentation only /after/ it has read a character. The »{« changes the indentation by 2, the »} by -2, but only after it was already encountered. So the change becomes visible at the line break following the indentation-changing symbol for the first time.
Mark Space - 01 Sep 2007 17:03 GMT >> Sure, but its only two lines more than >> if (a) { [quoted text clipped - 5 lines] > > if( a )b(); I notice you are doing something else: leaving white space in between the parenthesis and the term it encloses. I do this also. I'm not sure where I picked it up. I think it may have been a group of Ada programmers I hung around with in college.
But I've also been dinged for it in code reviews. This really frosts me. Dilbert-like attention to meaningless detail is the bane of corporate culture.
Stefan Ram - 01 Sep 2007 17:19 GMT >I notice you are doing something else: leaving white space in between >the parenthesis and the term it encloses. I do this also. I'm not sure >where I picked it up. I think it may have been a group of Ada >programmers I hung around with in college. It might be unrelated, but the Pet 2001 BASIC interpreter by Microsoft stored the token for »SIN« and similar calls as »SIN(«. So a programmer had no chance to see »SIN («.
>But I've also been dinged for it in code reviews. This really frosts >me. Dilbert-like attention to meaningless detail is the bane of >corporate culture. A paean of praise for this:
»I have never, ever, ever seen a great software developer who does not have amazing attention to detail.
[bells.jpg] I worked with a programmer back in school who forced anyone working with him to indent using two spaces instead of tabs. If you gave him code that didn't use two spaces he would go through it line-by-line and replace your tabs with his spaces. While the value of tabs is not even a question, (I've long-chided him for this anal behavior) his attention to such a small detail has served him well in his many years designing chips at Intel.«
http://www.softwarebyrob.com/articles/Personality_Traits_of_the_Best_Software_De velopers.aspx
Lew - 01 Sep 2007 18:24 GMT > I notice you are doing something else: leaving white space in between > the parenthesis and the term it encloses. I do this also. I'm not sure [quoted text clipped - 4 lines] > me. Dilbert-like attention to meaningless detail is the bane of > corporate culture. I would more likely ding you for omitting such spaces. They do enhance readability.
 Signature Lew
Matthias Buelow - 01 Sep 2007 18:34 GMT > I would more likely ding you for omitting such spaces. They do enhance > readability. No, they don't.</argument_clinic>
Lew - 01 Sep 2007 19:03 GMT Lew wrote:
>> I would more likely ding you for omitting such spaces. They do enhance >> readability.
> No, they don't.</argument_clinic> I made my comment in the first person to acknowledge the subjective nature of some of these "standards".
> Well, an argument's not the same as contradiction. ...
> An argument is a connected series of statements intended to establish a definite proposition.
 Signature Lew "Oh no, that's next door. It's being-hit-on-the-head lessons in here."
Matthias Buelow - 01 Sep 2007 19:29 GMT > An argument is a connected series of statements intended to establish > a definite proposition. You have to pay me if you want me to continue arguing with you.
Mike Schilling - 01 Sep 2007 19:32 GMT > Lew wrote: >>> I would more likely ding you for omitting such spaces. They do [quoted text clipped - 4 lines] > I made my comment in the first person to acknowledge the subjective > nature of some of these "standards". No, you didn't.
Martin Gregorie - 01 Sep 2007 23:53 GMT > But I've also been dinged for it in code reviews. This really frosts > me. Dilbert-like attention to meaningless detail is the bane of > corporate culture. There are a number of more or less acceptable ways of formatting code, but there's only one rule that a maintenance programmer should obey:
You WILL use the same indentation and naming rules as the original author no matter how abhorrent they may see to you.
I've seen far to much code turned into an unreadable dogs dinner by so called "programmers" failed to obey this rule.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Matthias Buelow - 31 Aug 2007 21:54 GMT > While I agree with Matthias's points about commenting the more obscure > parts of one's code, I cannot believe that he seriously is against the > use of Javadocs. Javadoc has advantages and disadvantages. The most prominent advantage is of course automated generation of reference documentation, however, I've found that the major disadvantage is that with javadoc comments, source code tends to get filled with some kind of textual styrofoam.
Patricia Shanahan - 31 Aug 2007 17:14 GMT >> For example, my code tends to be completely devoid of comments (because I >> find them distracting interspersed with the code -- the code itself should >> be expressive enough without all that chatter) > > Then you apparently have never implemented any more complicated or > non-intuitive algorithm... Or he may have put each non-intuitive algorithm in its own method, and included the algorithm outline and reference to its background in the Javadoc comment.
There is a school of programming that holds that a feeling that a block of code within a method needs a comment is a warning that it should have been a separate method.
>> -- except for JavaDocs, which >> I write copiously. It gives me a nice place to describe the class, member [quoted text clipped - 7 lines] > picture in comments and why you did some details the way you did them, > and not verbosely reformulate parts of the source code. That strategy works well if the program is small enough for every programmer working on it to read the whole program.
However, a lot of my work has been on programs with hundreds of thousands to millions of lines of source code. Often, all I care about is what a particular function is supposed to do and how it should be used. I love it when all that information is grouped in a comment at the start.
Depending on the source code to be self-documenting can lead to a nasty recursive process. "Recursive" both in the technical sense and in the sense of causing repetitive cursing on the part of the reader.
Suppose I'm reading A, and notice it may pass a null pointer to B. Is that OK or a bug? Without a detailed Javadoc comment, or equivalent, I have to read B to see what it does with null pointers. But B passes the pointer to C. Now I need to know how C deals with null pointers...
Patricia
Ed Kirwan - 31 Aug 2007 20:18 GMT > There is a school of programming that holds that a feeling that a block > of code within a method needs a comment is a warning that it should have > been a separate method. ...
> Patricia There seems to be a logical conclusion to this which does harbour some appeal, though I've never tried it myself.
It could be said that a method may contain only one of the following:
i) A set of non-method-calling statements. ii) A set of method calls. iii) A single if-then-else statement plus enclosed sets set of method calls . iv) A single iteration plus enclosed sets of method calls. v) A try/catch statement plus enclosed sets of method calls.
There's something pleasantly ... can't-go-lower-ish about it. Like finding the unsplittable atoms of execution. It even looks a little language-y, and might lend itself to (a form of meta-) parsing.
It also raises the question of degree. When does a method stand on its own two feet and when does it shatter into mini-methods? It would be nice to identify a mathematically describable property whereby we could chart an entire-class-in-a-method at one end, and an even more rigid method split than that defined above (say, rewriting (i) to allow a method to hold a maximum one non-method-calling statement). It would be nice to find where such a property's differential would hit 0.
 Signature .ed
www.EdmundKirwan.com - Home of The Fractal Class Composition
Ben Phillips - 31 Aug 2007 20:29 GMT > It also raises the question of degree. When does a method stand on its own > two feet and when does it shatter into mini-methods? It would be nice to [quoted text clipped - 3 lines] > maximum one non-method-calling statement). It would be nice to find where > such a property's differential would hit 0. You might be interested in googling "cyclomatic complexity". (The second hit is the Wikipedia article, and is probably the best place to begin.)
Matthias Buelow - 31 Aug 2007 21:58 GMT > You might be interested in googling "cyclomatic complexity". Software metrics are like Astrology -- interesting but useless.
Ed Kirwan - 31 Aug 2007 22:37 GMT >> You might be interested in googling "cyclomatic complexity". > > Software metrics are like Astrology -- interesting but useless. I like Robert Martin's quote on metrics, "However, a metric is not a god; it is merely a measurement against an arbitrary standard. It is certainly possible that the standard chosen ... is appropriate only for certain applications and is not appropriate for others. It may also be that there are far better metrics that can be used to measure the quality of a design."
Metrics certainly have severely limited value.
Calling them, "Useless," however, seems a little harsh. Matthias, I'm genuinely interested in hearing your experiences with them; it sounds like you have an interesting story to tell.
Metrics are just the degree to which machines (as opposed to humans) understand how good code is.
No, scratch that: metrics are just the degree to which a human can tell a machine how good a piece of code is.
And that's very, very limited.
But it's not nothing.
We can tell machines that there are some things that are easily recognisable as bad design, no matter what the scenario.
For example, circular dependencies.
Machines are great at finding circular dependencies, humans aren't (that's why we create them).
And just because a design has circular dependencies doesn't mean that it is rubbish (most popular projects on sourceforge have circular dependencies); but I've not yet come across a programmer who said that a good design should have circular dependencies.
OT: I've just started using KNode as my newsreader. It highlights misspellings as I type them. I know that's nothing new, but after coming from my old newsreader, it feels like wonderful magic. (Cue someone pointing out misspellings in this post.)
PS I like the way you capitalised, "Astrology;" it sort of lends that art a degree of respect against which that the rest of your mail railed, and gave your post a nice, literary tension.
PPS I wonder whether OTs should come before PSs in the grand scheme of letter-writing (of which newsgroup posts are the latest incarnation).
PPPS Can we also use OOT and OOOT in our posts?
PPPPS Or would OTT be more appropriate than OOT?
PPPPPS Oh, dear, Matthias, you may have just spawned an industry: computational astrology: the predictions of the success of a piece of software based on when it was written. I see my Fractality tool (began 24/02/2004, around 8pmish) is a Pisces, which means it's, "Imaginative and sensitive, Compassionate and kind, Selfless and unworldly, Intuitive and sympathetic." Good, then it's not, "Riddled with heinous bugs and doomed to misinterpret Java 6 bytecode for which it's still not updated to parse."
 Signature .ed
www.EdmundKirwan.com - Home of The Fractal Class Composition
Lew - 31 Aug 2007 23:47 GMT > PPS I wonder whether OTs should come before PSs in the grand scheme of > letter-writing (of which newsgroup posts are the latest incarnation). > > PPPS Can we also use OOT and OOOT in our posts? > > PPPPS Or would OTT be more appropriate than OOT? The reason for "PP...PS" is that the "P" stands for "post", meaning "after", so it's "after after after after .... after script".
Likewise, you would not say "off topic topic topic ... topic" but "off off off ... off topic" (like "off-off-off Broadway"), hence, "OOO...OT".
 Signature Lew
Matthias Buelow - 01 Sep 2007 17:01 GMT > Calling them, "Useless," however, seems a little harsh. Matthias, I'm > genuinely interested in hearing your experiences with them; it sounds like > you have an interesting story to tell. First, we have to clarify what kind of "Software Metrics" exist: structural metrics on procedural code, of Halstead's "Software Science" kind, like for example the "cyclomatic complexity" that has been mentioned. object-oriented metrics for computing certain class properties, and (attempts at) semantic metrics, which actually try to extract something sensible from the source.
Structural metrics are really banal -- despite their promising names, they essentially boil down to one thing: larger and more complicated code is harder to understand. They don't really make any more complicated statements. The "cyclomatic complexity", despite its intriguing formula, is essentially just counting the 'if's. The most primitive metric, LOC (lines of code) is the only one which is actually in wider use. Others, like the "program volume V*", are, as one researcher on semantic metrics (Baumann, 1991) said, "completely chaotic". There is no indication that they actually measure anything useful.
Object-oriented metrics measure things like the depth of an inheritance tree, number of children of a class, some weighted counting of methods per class, coupling between classes according to certain properties, etc., also relatively simple measurements. Like conventional structural metrics, they are measuring very superficial properties of the source code and have no insight into what the program is actually doing (or supposed to do). Some software managers say that they have a certain significance but I'm doubtful. At best, they can indicate some very superficial problems with the code.
A more sophisticated approach are semantic metrics, which try to infer some kind of semantical "information content" from the source by applying a theory of semantic and informational areas (with domain theory). However, last time I looked, there haven't really been any practical results, maybe there are now.
> Machines are great at finding circular dependencies, humans aren't (that's > why we create them). I'm not opposed to program analyzers in general. I'm just realistic about the well-known "software metrics" (typically Halstead's "software science", OO metrics by Chidamber & Kemerer, Briand, Devanbu, Melo etc.), which routinely get rehashed in software tools where they are being praised as powerful and indispensable development aids (by those who sell the software), whereas in truth they are just primitive, dated (Halstead's stuff is from the 70ies) and rather arbitrary measurements with very little, if any, practical significance.
> PS I like the way you capitalised, "Astrology;" it sort of lends that art a > degree of respect against which that the rest of your mail railed, and gave > your post a nice, literary tension. The reason is probably more profane; since I'm German, I occasionally capitalize nouns also in English, when I'm being careless.
> PPPPPS Oh, dear, Matthias, you may have just spawned an industry: > computational astrology: the predictions of the success of a piece of [quoted text clipped - 3 lines] > sympathetic." Good, then it's not, "Riddled with heinous bugs and doomed to > misinterpret Java 6 bytecode for which it's still not updated to parse." Written in the Year of the (Code-) Monkey!
Joshua Cranmer - 01 Sep 2007 14:44 GMT > You might be interested in googling "cyclomatic complexity". (The second > hit is the Wikipedia article, and is probably the best place to begin.) I have never placed much stock in cyclomatic complexity. Ten branches is way too few for anything even mildly complex. A lexer will probably easily breach 30 or so; a parser for something as simple as CSS would probably take 40+. Here's the big finale: a switch statement on a Java bytecode instruction. It's atomic and gives a cyclomatic complexity well beyond 100.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Karl Uppiano - 01 Sep 2007 23:17 GMT >> For example, my code tends to be completely devoid of comments (because I >> find them distracting interspersed with the code -- the code itself [quoted text clipped - 3 lines] > Then you apparently have never implemented any more complicated or > non-intuitive algorithm... Oh please...
>> -- except for JavaDocs, which >> I write copiously. It gives me a nice place to describe the class, member [quoted text clipped - 9 lines] > picture in comments and why you did some details the way you did them, > and not verbosely reformulate parts of the source code. I explan the big picture in the JavaDocs. By keeping methods short, I can constrain the number of operations to something that can be described in the JavaDocs. The biggest problem I have in maintaining other people's code usually involves non-descriptive variable names, unclear purpose of methods, member variables, parameters, return values and error conditions, which can all addressed in JavaDocs.
If I have a tricky algorithm that I need inline comments to describe, I take that as a hint that it should be in it's own method, complete with JavaDocs. The parameters, return values and exceptions in concert with the JavaDocs, become self-documenting.
> Unfortunately, your approach is typical for many Java (or industrial, > for that matter) programmers. I am not sure what you mean by this, but I take it perjoratively.
> I've seen quite some programs where the programmer said "don't have to > explain the stuff, the source code is obvious", which were basically > unmaintainable. So have I. But the proof is in the pudding. I have been writing software professionally since 1986 -- assembly, C, C++, Java and C#. I started doing JavaDoc-like comments when I was writing in C, and enthusiastically embraced JavaDocs when I first encountered them. People who have reviewed or maintained my code have remarked on the quality and maintainability. I do not say that boastfully -- but only to illustrate that something I am doing seems to be working.
Perhaps that is why coding is more an art than a cookbook activity. I suppose someone else could follow my recipe and end up with garbage.
Matthias Buelow - 01 Sep 2007 23:37 GMT > Perhaps that is why coding is more an art than a cookbook activity. I think it is.
Of course, "software-engineering" people have a totally different opinion on that.
They're wrong.
Sanjay - 31 Aug 2007 13:00 GMT > 'Good code' is code that works, is bug free, and is readable and > maintainable. Standards need to be followed for coding. Read more... > > http://brsx.co.uk/SWtesting/FAQs/FAQs012.asp • each line of code should contain 70 characters max.
Where the f.ck does that come from? 1970's? We just inherited shitty code from an outsourcing company where each line f.cking wraps around after some 50-100 characters for no reason. I have a f.cking 21 inch monitor and so does other developers and there is no one else going to look at the code besides developers why wrap around 70 characters?
Anyway nice try to get some ad revenue. One web page with three layers of google advertising.
Wildemar Wildenburger - 31 Aug 2007 14:11 GMT > • each line of code should contain 70 characters max. > > Where the f.ck does that come from? 1970's? We just inherited shitty > code from an outsourcing company where each line f.cking wraps around > after some 50-100 characters for no reason. Dude, you kiss your mother with that mouth? Whats wrong?
> I have a f.cking 21 inch monitor Really? I'd hate that, a monitor that constantly f.cks me ... and at 21 inches you're bound to feel it too. *sigh* To each his own.
> and so does other developers and there is no one else going to > look at the code besides developers why wrap around 70 characters? 1. It looks nicer if all lines have about the same length. 2. It makes it easier to grasp what's in the line. 3. Some people *do* still work in text terminals, you know.
> Anyway nice try to get some ad revenue. One web page with three layers > of google advertising. Ah, a good point, finally.
/W
Jeff Higgins - 31 Aug 2007 14:23 GMT > Dude, you kiss your mother with that mouth? Whats wrong? Thanks for the picture, greatly appreciated. JH
Lew - 31 Aug 2007 14:36 GMT >> Dude, you kiss your mother with that mouth? Whats wrong? > Thanks for the picture, greatly appreciated. > JH Java already has coding standards (although I always willfully violate them by putting the opening brace on its own line, aligned with the control statement): <http://java.sun.com/docs/codeconv/index.html>
I endorse line-wrap at 80.
 Signature Lew
Martin Gregorie - 31 Aug 2007 18:02 GMT > I endorse line-wrap at 80. Yep. An X-term console window defaults to 25 x 80.
I normally edit source with microEmacs or vi, view it with less and search it with grep, so compatibility with the default window size matters to me.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Lew - 31 Aug 2007 21:52 GMT >> I endorse line-wrap at 80. >> [quoted text clipped - 3 lines] > search it with grep, so compatibility with the default window size > matters to me. The exception probes the rule:
Sometimes if only a semicolon or close-parenthesis,semicolon sequence falls past the 80-column mark, I'll not wrap it. Console windows and most editors will wrap it for me, and there is little semantic confusion thereby.
I also indent with spaces, not tabs.
Another trick someone showed me years ago for in-code comments (as opposed to Javadoc comments) is to start them at some defined position, say, column 45 (1-based). Then you can read down the right side of the source listing and see comments, down the left side and see code.
Sort of like: /** Javadoc comments here. */ public void foo() { doSomething(); // do a vital thing cleanUp(); // close all connections logResults(); // log to system-defined output fireEvents(); // notify registered listeners }
Slash-star comments are good to introduce "paragraphs" of code with "paragraphs" of comment:
/* Initialize all connections. * Important to log any errors here. * INFO level used for additional diagnostic information. */
Connection cDb = openDbConnection(); Connection cXo = openXConnection(); ...
 Signature Lew
-- Lew
Mike Schilling - 31 Aug 2007 22:06 GMT > Another trick someone showed me years ago for in-code comments (as opposed > to Javadoc comments) is to start them at some defined position, say, [quoted text clipped - 10 lines] > fireEvents(); // notify registered listeners > } He had probably been an assembly-langauge programmer; it was very common for assemblers, especially those which read punched cards, to have fixed fields for (say) label, operator, operands, and comments, e.g.
start: mov r0 -(sp) push start address mov r1 -(sp) push size mov r2 -(sp) push destination address jsr copy copy block
Patricia Shanahan - 04 Sep 2007 00:34 GMT Mike Schilling wrote:
>> Another trick someone showed me years ago for in-code comments (as opposed >> to Javadoc comments) is to start them at some defined position, say, [quoted text clipped - 19 lines] > mov r2 -(sp) push destination address > jsr copy copy block I like this style of comment in assembly language code, but dislike it in high level languages.
If, for example, "cleanUp" really means "close all connections" why not rename it "closeAllConnections" and remove the comment? A comment that fits at the end of the line is unlikely to add much to a line of high level language code with meaningful identifiers.
Patricia
kaldrenon - 04 Sep 2007 00:53 GMT > I like this style of comment in assembly language code, but dislike it > in high level languages. [quoted text clipped - 5 lines] > > Patricia My personal little addition to this advice (with which I otherwise heartily agree) is that brevity is still nice. Not nice enough to be worth the sacrifice of meaning, but still nice.
For example, there's no significant difference in clarity between:
closeAllNetworkConnections closeAllNetConnections closeAllNetConns (unless you have reason to believe someone might not recognize the abbreviation of Conns for Connections, but I consider that common knowledge to a developer)
But IMHO, the last of these three is superior because it's clear what it means, but it's shorter, which keeps the lines on which it appears shorter, and is (slightly) less typing. In most examples the difference is trivial, but once a variable, class, or method name gets about about 15 characters I start to cringe.
Patrick May - 04 Sep 2007 01:08 GMT >> If, for example, "cleanUp" really means "close all connections" why >> not rename it "closeAllConnections" and remove the comment? [ . . . ]
> For example, there's no significant difference in clarity between: > [quoted text clipped - 7 lines] > what it means, but it's shorter, which keeps the lines on which it > appears shorter, and is (slightly) less typing. I suggest that the first of these is superior because it is very explicit about the purpose of the method. Programmers reading the code won't have to mentally expand any abbreviations and programmers using the method won't have to try to remember which choice of abbreviations the original programmer made: "Was that closeAllNetConn(), closeAllNetConns(), closeAllNetworkConns(), . . . ."
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | Large scale, mission-critical, distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, middleware, SOA)
kaldrenon - 04 Sep 2007 02:07 GMT > >> If, for example, "cleanUp" really means "close all connections" why > >> not rename it "closeAllConnections" and remove the comment? [quoted text clipped - 18 lines] > closeAllNetConn(), closeAllNetConns(), closeAllNetworkConns(), > . . . ." A very good point. Once again I catch myself thinking more in terms of what I want to do when coding than in terms of what is best for teamwork, maintenance, etc.
Patricia Shanahan - 04 Sep 2007 01:14 GMT ...
> For example, there's no significant difference in clarity between: > [quoted text clipped - 9 lines] > difference is trivial, but once a variable, class, or method name gets > about about 15 characters I start to cringe. I agree with this if, and only if, "conns" is consistently used for "connections" in identifiers throughout.
Patricia
Arne Vajhøj - 04 Sep 2007 01:22 GMT > Mike Schilling wrote: >>> Another trick someone showed me years ago for in-code comments (as [quoted text clipped - 29 lines] > fits at the end of the line is unlikely to add much to a line of high > level language code with meaningful identifiers. You may not be in control of the method names.
Arne
Patricia Shanahan - 04 Sep 2007 01:36 GMT ...
>> If, for example, "cleanUp" really means "close all connections" why not >> rename it "closeAllConnections" and remove the comment? A comment that >> fits at the end of the line is unlikely to add much to a line of high >> level language code with meaningful identifiers. > > You may not be in control of the method names. True, but the cases of inappropriate and unfixable method names should be the exception, not the driver for the normal commenting conventions.
Patricia
Martin Gregorie - 05 Sep 2007 12:04 GMT > Mike Schilling wrote: >>> Another trick someone showed me years ago for in-code comments (as [quoted text clipped - 24 lines] > I like this style of comment in assembly language code, but dislike it > in high level languages. However, it can degenerate into silliness, e.g. TSC programmers (the folks behind Flex09 in case you care) invariably wrote:
INX Increment the X register
which added nothing except increased size to the source file. Its all too easy to do this on any language and is to be avoided.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Stefan Ram - 05 Sep 2007 13:53 GMT >>>>doSomething(); // do a vital thing >>>>cleanUp(); // close all connections [quoted text clipped - 3 lines] >which added nothing except increased size to the source file. Its all >too easy to do this on any language and is to be avoided. I have a refactoring habit »replace names by their comments« for code such as quoted indirectly above. By this rule, the code is refactored into the following code, which uses a '...'-notation implemented by a preprocessor I use for Java:
'do a vital thing'(); 'close all connections'(); 'log to system-defined output'(); 'notify registered listeners'();
My preprocessor will transform this to:
doAVitalThing(); closeAllConnections(); logToSystem_45_definedOutput(); notifyRegisteredListeners();
Lew - 05 Sep 2007 14:50 GMT > 'log to system-defined output'(); > > My preprocessor will transform this to: > > logToSystem_45_definedOutput(); What an unfortunate choice. The "45" loses the self-documentation quality, looking as it does like a magic number, and underscores are against Sun's recommended method-naming conventions.
 Signature Lew
Martin Gregorie - 01 Sep 2007 14:12 GMT > I also indent with spaces, not tabs. So do I, for one good reason: most OSen[1] don't allow you to specify the length of a tab. Most source editors (vi, microEmacs, PFE, ....) do, but changing the tab spacing causes them to use spaces instead.
The near universal standard tab space of 8 characters is way too long - 3 or 4 characters is about right.
[1] Microware's OS-9 is the honorable exception: tab spacing is configurable at the terminal driver level and can be retrieved by any program that needs to know what it is. The OS-9 default tab spacing is 4 characters - a sensible value.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Mike Schilling - 01 Sep 2007 16:58 GMT >> I also indent with spaces, not tabs. >> > So do I, for one good reason: most OSen[1] don't allow you to specify > the length of a tab. Most source editors (vi, microEmacs, PFE, ....) > do, but changing the tab spacing causes them to use spaces instead. Or to mix tabs and spaces (4 spaces for one level, a tab for two levels, etc.). If you're working in a team, it makes far more sense to use spaces than to insist everyone use an editor that treats tabs identically.
Sanjay - 31 Aug 2007 16:23 GMT >> • each line of code should contain 70 characters max. >> [quoted text clipped - 3 lines] > > > Dude, you kiss your mother with that mouth? Whats wrong? Lets keep my and your mother out of this. You stick to the things I am talking about and don't mention my mother again. Thank you.
Thomas Fritsch - 31 Aug 2007 17:06 GMT >>> • each line of code should contain 70 characters max. >>> [quoted text clipped - 6 lines] > Lets keep my and your mother out of this. You stick to the things I am > talking about and don't mention my mother again. Thank you. Sanjay, remember, it was you who started to use lots of aggressive and derogative words. (See the quoted lines above.) Wildemar Wildenburger just replied in a way similar to yours.
I understand that you have bad emotions about your inherited code. But be aware: writing with strong emotions probably causes replies with the same strong emotions. So calm down, stick to the things, talk about the facts in an appropriate way, and you will get the polite answers you want.
 Signature Thomas
Twisted - 31 Aug 2007 19:34 GMT On Aug 31, 9:11 am, Wildemar Wildenburger <lasses_w...@klapptsowieso.net> wrote:
> > I have a f.cking 21 inch monitor > > > > Really? I'd hate that, a monitor that constantly f.cks me ... and at 21 > inches you're bound to feel it too. *sigh* To each his own. Ouch...
> > and so does other developers and there is no one else going to > > look at the code besides developers why wrap around 70 characters? > > 1. It looks nicer if all lines have about the same length. > 2. It makes it easier to grasp what's in the line. > 3. Some people *do* still work in text terminals, you know. Yeah, I know -- those nutters from comp.emacs whose attempted invasion of this newsgroup I foiled a few weeks ago. :)
Joshua Cranmer - 31 Aug 2007 14:45 GMT >> 'Good code' is code that works, is bug free, and is readable and >> maintainable. Standards need to be followed for coding. Read more... [quoted text clipped - 8 lines] > monitor and so does other developers and there is no one else going to > look at the code besides developers why wrap around 70 characters? Right now, I am stuck with a 1024x768 resolution, so anything more than ~90 characters starts wrapping around. Obviously, you have never tried to edit a line of code in vim that has wrapped around 3-4 times.
I do, however, agree that 70 characters is too short for a reasonable line; 80-90 characters is a better limit.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Sanjay - 31 Aug 2007 16:35 GMT >>> 'Good code' is code that works, is bug free, and is readable and >>> maintainable. Standards need to be followed for coding. Read more... [quoted text clipped - 15 lines] > I do, however, agree that 70 characters is too short for a reasonable > line; 80-90 characters is a better limit. Of course I use vi or vim or pico or nano whenever I am working on solaris terminal writing or debugging shell scripts (I use kate or Quanta on linux). However I have never used vi for writing J2EE code. For that I always use either eclipse or WSAD depending on the application server.
I guess I can safely assume we are talking about java or jEE here rather than shell script. If you are saying you are writing Java code in vi you seriously have to upgrade to some IDE in order to make your life easier. That is of course IMHO.
Joshua Cranmer - 31 Aug 2007 18:34 GMT > I guess I can safely assume we are talking about java or jEE here rather > than shell script. If you are saying you are writing Java code in vi you > seriously have to upgrade to some IDE in order to make your life > easier. That is of course IMHO. Actually, the project I'm referring to is a PHP project that is hosted on a remote development sandbox server with no GUI access. [*] Second, I'm using vim and not vi, and I do very heavily use the extensions built into vim.
[*] Actually, I could open up an X-session tunneling on SSH, but the computer's slow enough without trying to piggyback on SSH -X session over another SSH session.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Matthias Buelow - 31 Aug 2007 15:35 GMT > Where the f.ck does that come from? 1970's? We just inherited shitty > code from an outsourcing company where each line f.cking wraps around > after some 50-100 characters for no reason. I have a f.cking 21 inch > monitor and so does other developers and there is no one else going to > look at the code besides developers why wrap around 70 characters? I think it's a good idea not to make stuff "too wide". That doesn't mean to slavishly stick to a certain columns limit, though. Use some common sense and aesthetics (most people don't seen to have a sense for this, though.)
Patrick May - 01 Sep 2007 02:05 GMT >> 'Good code' is code that works, is bug free, and is readable and >> maintainable. Standards need to be followed for coding. Read more... [quoted text clipped - 4 lines] > > Where the f.ck does that come from? Legibility. Newspapers are a good example. The reason they use multiple columns is because humans can only easily scan a limited number of characters on a single line.
The established standard of between 72 and 80 characters is close enough to the ideal that there is no good reason to violate it.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | Large scale, mission-critical, distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, middleware, SOA)
~kurt - 01 Sep 2007 02:24 GMT > Where the f.ck does that come from? 1970's? We just inherited shitty And if it does, what is the problem? Really, what have we accomplished since the late 60's that is really of any worth? They had some smart people back then.
> code from an outsourcing company where each line f.cking wraps around > after some 50-100 characters for no reason. I have a f.cking 21 inch Some of us like to have multiple edit windows open and viewable at the same time, on the same screen. People who don't wrap at or near FORTRAN standards should be shot.
> Anyway nice try to get some ad revenue. One web page with three layers > of google advertising. I'm not clicking on it.
- Kurt
Joshua Cranmer - 02 Sep 2007 00:30 GMT (More or less in response to the entire thread)
How ironic it is that no one has written a file system that can transparently convert between different formats, so that person A would see:
if ( foo ) { ... } else { ... }
and person B sees: if (foo) { ... } else { ... }
(note use of tabs).
Heck, they might even make it translate between getFoo, GetFoo, and get_foo (binary compatibility not guaranteed)!
Hmmm... it would have to involve extensive use of metadata (so that FORTRAN files are not formatted as Java files), but if it could be made relatively painless, it would probably find widespread use...
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Matthias Buelow - 02 Sep 2007 02:21 GMT > Heck, they might even make it translate between getFoo, GetFoo, and > get_foo (binary compatibility not guaranteed)! Actually emacs can do something like that (glasses-mode), it then displays all CamelCaseIsHardToRead as Camel_Case_Is_Hard_To_Read, which is a easier to read for some people. While keeping the original style in the source text, of course. Quite nifty.
Roedy Green - 02 Sep 2007 06:36 GMT On Fri, 31 Aug 2007 06:05:29 -0000, "davidsamith@gmail.com" <davidsamith@gmail.com> wrote, quoted or indirectly quoted someone who said :
>'Good code' is code that works, is bug free, and is readable and >maintainable. Standards need to be followed for coding. Read more... see http://mindprod.com/jgloss/codingconventions.html
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Free MagazinesGet 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 ...
|
|
|