JSPWiki Coding standard#


I tend to follow the Avalon Coding Standards as much as I can, and I much prefer them over the official Sun Java Coding Conventions. Since I seem to be explaining these things separately to everyone, I'll try to explain my thoughts on the subject.

As a bit of a background, I've been coding roughly 17 years now - I think I sold my first (BASIC) program about then. I've also read about a zillion lines of other people's codes, and have been strongly influenced by a few people, who write crystal-clear, beautiful code. (Jan van den Baard and Ari Lemmke, especially).

--JanneJalkanen, 13-May-2002.

Separate class, instance, and local variables.#

The Java Coding Conventions don't really make much difference between whether your variable is local, instance (=member), or class (=static). This can make the side-effects of an assignment quite unobvious, and this is why I use the following convention myself:

  • Class variables should be prefixed with "c_".
  • Member variables should be prefixed with "m_".
  • Local variables, including parameters, should be written in the usual Java Coding Convention style (smallThenCapital).

It is also true that this removes the need of using explicit this almost completely. See WhyUsingThisIsBad.

Braces go on their own lines.#

The major source of dreaded CurlyBraceWars. The reason why I write the starting curly brace on a new line is this:

    if( foobar.equals("blat") && 
        doStuff() < 15 || doStuff() > 30 ) {
        goAway();
    }

It's kinda hard to see where the if-condition ends, and where the block starts. So, it's much better to write:

    if( foobar.equals("blat") && 
        doStuff() < 15 || doStuff() > 30 ) 
    {
        goAway();
    }

Which is immediately clear.

People often tell me that this means that your code becomes much longer and thus since you can't easily fit it on a screen, it becomes less readable. I say that your code has other problems if you can't write your method so that it fits on the screen, and you can't solve them by changing the place of your curly braces. You must refactor mercilessly.

Note that especially with Java, your method calls and declarations often become very long:

    public String textToHTML( WikiContext context,
                              String pagedata,
                              StringTransmutator localLinkHook,
                              StringTransmutator extLinkHook )
    {
        String result = "";
        // Code goes here.
    }

Now, if you put the brace after the end of the last line, and compare:

    public String textToHTML( WikiContext context,
                              String pagedata,
                              StringTransmutator localLinkHook,
                              StringTransmutator extLinkHook ) {
        String result = "";
        // More code.
    }

The Java Coding Convention advocates that you should use this instead:

    public String textToHTML( WikiContext context,
            String pagedata,
            StringTransmutator localLinkHook,
            StringTransmutator extLinkHook ) {
        String result = "";
        // More code.
    }

but frankly, I find this even more horrible. It's sort of a retrograde kludge to fix the problem that happened with the wrong decision of not putting the curly brace on its own line in the first place. In fact, now you can't even immediately see which parameters the method takes.

Here's something you could do, though (and I do this sometimes myself, but I haven't yet decided whether it's worth the effort or not):

    public String textToHTML( WikiContext        context,
                              String             pagedata,
                              StringTransmutator localLinkHook,
                              StringTransmutator extLinkHook ) 
    {
        String          result = "";
        StringTokenizer st     = new StringTokenizer();
        // More code.
    }

In some cases, this makes the argument list much more understandable (since usually you need to scan for either the types of the arguments, or the names of the arguments).

else while catch finally
appear to go on new lines as well -- KenLiu

Indent at 4 spaces, NO TABS!#

Do not use tabs. Why tabs are evil?.

Spaces go around the arguments, not around the keywords.#

Some people use:

    if ((a==b)&&(c()==d)&&(d==f())) 

I find:

    if( (a == b) && (c() == d) && (d == f()) )
much clearer. Why? The explanation for the space after the "if" is that since "if" is a language-specific keyword, and not a method, it should be made visible somehow. I say that if you can't tell if() from a method call, you probably shouldn't be coding Java in the first place.

Anyway, the interesting part is not the if(). The interesting part is the logic of what the condition actually means, and thus that should be made a) prominent, and b) clear.

Screw the 80 character line length mantra.#

We no longer have to code on 80x25 teletypes. Especially with Java, class names, method calls, declarations, etc. become easily over 80 characters. It is not good practice to use shorter variable, and method names so that you could accommodate some people who insist on using 80 character teletypes.

OK, it is a good idea to limit your line length. But don't do it at the expense of readability. Try to wrap around 80, but don't feel bad if you need to go overboard.

Comments#

Within Javadoc, prepend all lines with '*':s, even though it may seem cumbersome. This is because Javadoc in 1.3 was buggy, and might screw your <pre>-sections for example. Also, I find that it makes the method stand out better.

Within code, use // to make block comments:


    Foo();

    //
    //  Now we'll go and do stuff.
    //  Note that this code does not really work when the moon is full,
    //  but since this occurs very rarely, we don't need to worry about it.
    // 

    Bar( new Date() );

Using // instead of /*...*/ allows you to comment out code. Since Java's /* comment markers do not nest, you would get into problems if you wanted to comment out an entire method for debugging purposes or something.

Note that you should not put out code with long commented sections anyway - they definitely reduce readability. Or if you have to comment out code, then use //, since it makes immediately clear which lines are commented out.

Commenting in general#

Actually, I believe that commenting and documentation is just an excuse for not writing clear code. Unfortunately, there are not many people who can write code that's just so obvious, that you don't need to comment it, and thus commenting is a must for the rest of us.

But still, if a piece of code is non-obvious, it's better to refactor it and make it more readable. And this goes for everyone else's code as well - if you have proper tests in place, then you should not fear changing code. You must be bold and refactor mercilessly. Coding is not for the weak-minded - if you're afraid to change a piece of your own code, you're doing something wrong.

Using Javadoc @version#

I'm sort of two minds about this: First of all, using the @version by hand adds a lot of trouble. More often than not, people forget to bump the revision number when they make a small change. Revision tracking should be the problem of the revision control system anyway.

However, using CVS and the embedded $Revision will cause problems when you do branches and merges. So beware.

Do not use "this"#

There is an ongoing discussion whether an explicit this is bad. See WhyUsingThisIsBad, for more comments on the matter.

At any case, JSPWiki codebase does not use this except where absolutely required.


Eclipse profile#

An easy way to get this coding standard working in your Eclipse environment is to import this Eclipse formatting profile(info)

Discussions#

RE: Spaces go around the arguments, not around the keywords.#

I read recently that programmers spend 90% of their time reading code and only 10% actually writing it. Our mental model for parsing text, the way we have been taught since childhood, so that it is thoroughly ingrained is to use spaces to separate syntactic units.

Using spaces artificially, to be interpreted as a code to indicate lexical features, strikes me as counter-productive. It is actually introducing extra complexity. Do I really need to see a language 'word' (if) jammed up against an opening parenthesis -- somthing you'd never see in a regular text -- to recognize that it is not a method!!

The 'rule' isn't even handled consistently here. In one place we see:

  if( foobar.equals("blat")
while in other places we see:
  foobar.methodCall( arg1, ... )

I recommend punctuating code as if it were regular text. For example,

  if (foobar.equals ("blat")) {...}

--David Phillips

David, just looking at the above line formatted as you suggest makes me cringe. I couldn't imagine trying to read an entire page of code formatted that way. --Kevin Berndsen


(More stuff to come, as I get more steam again. --JanneJalkanen. In the meanwhile, here's a good document to producing unmaintainable code.


In some of our discussions I've seen arguments for or against certain stylistic conventions (particularly on whitespace or braces) tagged pejoratively as an aesthetic argument. Well, given that from a machine's perspective all of this is pretty irrelevant, it's all aesthetics. That said, I just looked at a few of the classes from CVS that I'd written but have recently been reformatted and I find them harder to read. My own code. While I don't have a problem with the position of braces, changing

  if ( boolean )
  synchronized ( )
to
  if( boolean )
  synchronized( )
makes it harder for me to recognize those constructs. I don't believe there's any valid argument against whitespace around any kind of tokens. If it makes it easier to read them, i.e., to pick them out from all manner of other syntax, if it makes it easier for us when we're coding, then any arguments that this is simply aesthetics should be discounted; this is a matter of simple ergonomics. This is the point at which this "standardization" starts to get a bit irritating, and that's when I'm having trouble reading my own code (content I'm very familiar with). Not a great deal of trouble on a per-instance basis, but if the "if" token no longer stands alone I have to take extra effort to notice it. Magnified over the thousands of time I scan code this is a problem. "if" is not a method call, do we have to treat it as one at the expense of readability?

-- MurrayAltheim

Well, once you check it in it stops being your code. It's common code. And this is the coding standard used in JSPWiki, so all code must be formatted accordingly.

(And actually, I find this style more readable than the whitespaced one, because the braces are not really a part of the construct. To me they're visual distraction.)

-- JanneJalkanen

I understand that perfectly well. I've been coding for almost three decades, so this is hardly the first time I've encountered coding conventions as a team requirement. And this is your project — no argument there. As such, it's your prerogative to make these demands, but by not following existing guidelines (which are often the product of thousands of programmer's inputs, e.g., Apache, IBM, JavaSoft) means we end up with everyone else having to change their habits to a custom set of conventions that only hold for this one project. Every other project I'm on right now uses the Sun conventions or some variant on them. You'ves said that the JSPWiki guidelines are based on those of Avalon, an Apache project that closed in 2004. Notably, all current Apache code must comply with Sun's Java guidelines or minor variants thereof, which if anything usually suggest more whitespace (e.g., 1, 2, 3, 4, 5, 6).

You're quite correct and I agree: the braces are not part of the construct, nor since this isn't a method call are they part of the if, which would suggest that they shouldn't butt up against it. But one might characterize this as an aesthetic argument. To me this isn't a matter of better or worse or aesthetics, it's simply a pragmatic request to reconsider that extra whitespace after the if for practicality' sake: I find it harder to read it the way your guidelines demand, the if is harder to pick out when scanning. I find it visually distracting to not be able to locate the if statements as easily as if following either the Sun or Apache guidelines. Note that I'm not suggesting eliminating the whitespace around the parenthesized construct, I'm suggesting permitting an optional space character (which was and is still permitted in Apache projects). An extra space is not distracting, but lack of it certainly can be.

-- MurrayAltheim

The logic behind the position of braces#

It's good to see the logic of brace positioning discussed/rationalised. Almost all the coding standard papers I read say something like:

  • Place opening braces at the end of the line
    Rationale: it looks neater

And never go on to explain why it looks neater.

It's only recently I've learned the reason behind having the opening brace onto the same line as the controlling condition (to save space, apparently) and I can't get over how this logic, this coding standard has penetrated so much code without people questioning why.

Coming from a mathematics and physics background I find it easy to explain why opening braces on the next line look neater. It's simply a measure of entropy.

    if ( (a == b) && (b < c) ) {
        doSomethingSpecial( a, b, c );
        doSomethingElse( a, b, c );
        takeABow();
    }
    ^
^^^ 2 things line up (1 if, 1 brace)
    if ( (a == b) && (b < c) )
    {
        doSomethingSpecial( a, b, c );
        doSomethingElse( a, b, c );
        takeABow();
    }
    ^
^^^ 3 things line up (1 if, 2 braces)

There is more order in the second example, so there is less entropy. In scientific terms the code is more tidy.
The problem is people become used to reading code formatted in a particular way. Having braces at the end of a line may be more familiar to some people but it certainly isn't neater.

--Steve Battey, 21-Feb-2007

Is there a Jalopy config XML file (or similar) we can use to format to the preferred JSPWiki code style? --Jason Thrasher, 26-Feb-2007

Add new attachment

Only authorized users are allowed to upload new attachments.

List of attachments

Kind Attachment Name Size Version Date Modified Author Change note
xml
jspwiki-coding-conventions.xml 26.9 kB 1 10-Nov-2007 20:34 HarryMetske /jspwiki-coding-conventions.xml
 
mycodingconventions 26.9 kB 1 27-Feb-2007 13:11 JanneJalkanen
« This page (revision-36) was last changed on 14-Apr-2008 00:04 by JanneJalkanen