Computer Science Canada

Coding Conventions!

Author:  the_short1 [ Wed Jul 19, 2006 8:36 pm ]
Post subject:  Coding Conventions!

Well, it seems like lots of ppl dont know the proper code conventions (And yes im guilty to not following all of them myself), but I try to follow them and its a good thing to get into the habit of.

Here is a link I found recently, and I thought I would share
http://java.sun.com/docs/codeconv/

I recomend the .pdf form for ease of reading through the whole thing (vs HTML)

-Kevin

Author:  Aziz [ Thu Jul 20, 2006 7:55 am ]
Post subject: 

That being said, kevin, what form brackets do you use?

Sun says the

Java:
public void method() {
  //Some code
}


is the preferrable way, but many people (including well experienced programmers) use a more, erm, explicit (isn't the exact word but it'll do), way (although it does result in more whitespace):

Java:
public void method()
{
  //Some code
}


While both are organized (as long as you use them correctly!) Is there anything really against the latter one? I've know it makes the code a bit longer, but it's also really readable (and not to mention a hard habit to break). The point is, should the braces convention be strictly to the former way? In you opinion?

Author:  [Gandalf] [ Fri Jul 21, 2006 3:59 am ]
Post subject: 

It's simply a matter of the preference of the community. The Java people prefered the braces kept on the same line and made that the standard. In many other languages, the community settled on putting them on a new line, and that became the convention. They both have merits, so it really comes down to your choice of which to use. What's more imporant than this choice is that you keep a consistent style throughout your code.

Author:  the_short1 [ Fri Jul 21, 2006 11:33 pm ]
Post subject: 

Well said gandalf..

Personally, ive always used the { being on the same line without knowing the coding conventions, and i was glad to read that i was doing it in the right Smile In my opinion, I find it easier to trace back the origin by having less curly braces and brackets to muddle it up..as well, i will use whitespace when needed of course, but overall i like compactness and the prefered method gives me that.

but as for if else statements, ive always used this form...
code:

if (condition == blah){
    //code
}
else{
    //code
}

I just started adapting to the standard form "}else{"and its not bad, keeps related if else more "together".. so i like it...thing im most guilty of is my comment structure sucks, and i tend to have a lot of messy tailing comments...i dont like putting them on there own line...What about you, what conventions do you directly follow / guilty of not doing right?

edit: they discourage having no curly braces if only 1 action per if statement, but its just soo excessive to have them if you have several if statements with only 1 action line..... but i guess switch case is a better alternative then...

Author:  Aziz [ Sat Jul 22, 2006 12:21 pm ]
Post subject: 

I still like to use the braces on a new line. I've just been used to it and I'm usually over-organized. But I like it because I can see my code block right away. I used to use the on-line if statements with no brackets, but after reading that article, I don't. They're point is really good. If you add another line in after testing, or especially a few weeks/months down the road, it's not going to work the way you want it, especially in places where it's not evident (algorithms and background calculations). Find an error in drawing is pretty easy, but it can be hard to trace in the debugging process.

In really short if's i put the statement, braces and code all on one line:

Java:
if (*expression*) { statement; }
else if (*expression*) { statement; }
else { statement; }


or in my current project something like (more organized):

Java:
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();
       
        //Handle commands
        if (cmd.equals(IN)) // Punch In button
        { actionIn(); }
        else if (cmd.equals(OUT)) //Punch Out button
        { actionOut(); }
        else if (cmd.equals(EDIT)) //Edit button
        { actionEdit(); }
        else if (cmd.equals(DEL)) //Delete button
        { actionDelete(); }
        else if (cmd.equals(CALC)) //Calculate button
        { actionCalc(); }
        else if (cmd.equals(SAVE)) //Save button
        { actionSave(); }
        else if (cmd.equals(PRINT)) //Print paystub button
        { actionPrint(); }
    }


or for try/catch blocks, when you don't have to catch anything.

Java:
try
{
   //some code
}
catch (Exception e) {}


Really, code conventions IMO are guidelines, not rules. If it's still readable, then it should be good. Shortcuts like this can improve readability, if used right. A bad example:

Java:
if (a == 5 || a == 3 || a == 7 || name.equals("Joe") || !keepGoing) {a = b; name = "Fudgecake"; b++; System.out.println(name + a/b);}


A good idea would probably show it to a fellow programmer and see if they can understand. You see so many posts here with somebody trying to get help and the first reply is "What's this *code snippet* supposed to be?". I think somebody should write a walk-through tutorial on right proper code.

Author:  wtd [ Sat Jul 22, 2006 12:29 pm ]
Post subject: 

Understanding why the guidelines are what they are is about a million times better than just blindly following them.

Author:  wtd [ Sat Jul 22, 2006 12:31 pm ]
Post subject: 

Oh and just say no!

code:
        if (cmd.equals(IN)) // Punch In button
        { actionIn(); }
        else if (cmd.equals(OUT)) //Punch Out button
        { actionOut(); }
        else if (cmd.equals(EDIT)) //Edit button
        { actionEdit(); }
        else if (cmd.equals(DEL)) //Delete button
        { actionDelete(); }
        else if (cmd.equals(CALC)) //Calculate button
        { actionCalc(); }
        else if (cmd.equals(SAVE)) //Save button
        { actionSave(); }
        else if (cmd.equals(PRINT)) //Print paystub button
        { actionPrint(); }


By the way, is there some reason that you don't have action listeners on each widget, that would remove the need for this kind of dispatch mechanism?

Author:  Aziz [ Sat Jul 22, 2006 12:50 pm ]
Post subject: 

wtd wrote:
Understanding why the guidelines are what they are is about a million times better than just blindly following them.


Very true, such as the if statement conventions, always using braces. I'm a sinner, though, sometimes, as I'm lazy. I usually (well I make a point to) go back and fix up my programs after they're done and I see what needs changing.

wtd wrote:
By the way, is there some reason that you don't have action listeners on each widget, that would remove the need for this kind of dispatch mechanism?


Yes. The reason would be that I haven't looked into it yet and that I referred to my last project for reference, as I haven't touched Java, let alone SWING, in a bit. I'm going to check it out and see what to do with it right now, actually. Thanks, I probably would've left it that way Embarassed

Author:  wtd [ Sat Jul 22, 2006 12:54 pm ]
Post subject: 

I find that Java as a language (leaving the VM and library out of the debate) is not terribly powerful, but anonymous inner classes are one of the better things it provides.

Author:  Aziz [ Sat Jul 22, 2006 1:21 pm ]
Post subject: 

wtd, what exactly do you mean? This is what I'm doing right now:

I'm only using buttons, no toolbar, so I don't think I'll benefit from using an Action. Here's the buttons:

Java:
        inButton = makeButton("Punch In", IN);
        outButton = makeButton("Punch Out", OUT);
        editButton = makeButton("Edit", EDIT);
        deleteButton = makeButton("Delete Last", DEL);
       
        calcButton = makeButton("Calculate", CALC);
        saveButton = makeButton("Save", SAVE);
        printButton = makeButton("Print Paystub", PRINT);


and the makeButton() method:

Java:
    private JButton makeButton(String text, String actionCommand)
    {
        JButton b = new JButton(text);
        b.addActionListener(this);
        b.setActionCommand(actionCommand);
       
        return b;
    }


and then the actionPerformed() method from ActionListener interface:

Java:
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();
       
        //Handle commands
        if (cmd.equals(IN)) // Punch In button
        { actionIn(); }
        else if (cmd.equals(OUT)) //Punch Out button
        { actionOut(); }
        else if (cmd.equals(EDIT)) //Edit button
        { actionEdit(); }
        else if (cmd.equals(DEL)) //Delete button
        { actionDelete(); }
        else if (cmd.equals(CALC)) //Calculate button
        { actionCalc(); }
        else if (cmd.equals(SAVE)) //Save button
        { actionSave(); }
        else if (cmd.equals(PRINT)) //Print paystub button
        { actionPrint(); }
    }


All the sources I've checked (including The Java Tutorial and the Java Almanac) do it this way, or using an source = e.getSource() method, unless that's what you mean? Thanks wtd.

Author:  wtd [ Sat Jul 22, 2006 2:33 pm ]
Post subject: 

code:
JButton inButton = new JButton("Punch In");
inButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        actionIn();
    }
});


Of course, there's a good change the code in actionIn should just be moved into the inner class, but I'm just working with what's provided.

Or in Scala, where it looks nicer. Wink

code:
val inButton = new JButton("Punch In") with ActionListener {
    def actionPerformed(e: ActionEvent) = actionIn
}

Author:  Aziz [ Sat Jul 22, 2006 2:40 pm ]
Post subject: 

So I shouldn't use separate methods for actions, just all the code inside the addActionListener() bit? I have another question but I'll post a new topic, to avoid spamming this post (what happened to 'code conventions tutorial' Razz)

Author:  the_short1 [ Sat Jul 22, 2006 3:15 pm ]
Post subject: 

Aziz wrote:
So I shouldn't use separate methods for actions, just all the code inside the addActionListener() bit? I have another question but I'll post a new topic, to avoid spamming this post (what happened to 'code conventions tutorial' Razz)


yea .. good idea Smile i acually replied to your question before wtd posted, but i didnt hit the post button until 5minutes after he posted so i had to delete it .. lol.... Smile Yea .. .code convetions... about that...

Author:  Aziz [ Sun Jul 23, 2006 3:25 pm ]
Post subject: 

In topic, what about commenting? Shouldn't there be at least some standard or convention, even a general tip, about commenting? Like, when to use the different types: one-line, block, and end-of-line, for example, and when not to use commenting at all.

Author:  wtd [ Sun Jul 23, 2006 3:37 pm ]
Post subject: 

There are good conventions for this.

The first guideline: Don't use comments to say something that the code already says. It is the responsibility of the person reading your code to know the language the code is written in. Do not coddle readers.

Comments should, if necessary, explain the intent of a piece of code. "Why are you incrementing that accumulator variable?" That said, do not comment common idioms. Again, you are not responsible if the person reading your code is an idiot. If they are, and for some reason it is your problem, then make sure they understand those idioms in general, before reading your code.

Place comments above the code they refer to. Not after or beside. Before.

Use line comments when you only want one line. Use multi-line comments when you need multiple lines of comment.

Do not let a comment stretch more than 80 characters wide.

Use documentation comments when you want an explanation to appear in documentation.

Author:  Aziz [ Sun Jul 23, 2006 10:01 pm ]
Post subject: 

Are end-of-line comments always a no-no? A read an article that said never use them, but what about where it simply describes something in a list of said somethings.

code:
//Add components to frame
frame.add(topPane);      //Top panel, contains header title.
frame.add(middlePane);   //The middle panel, contains forms.
frame.add(bottomPane);   //The bottom panel, contains status bar.


Does this take away from it? I haven't been doing it much, but I know what I'm doing, and I don't really look at other peoples' code too much. You have, wtd, is it a pain in the ass when these comment are around?

Author:  wtd [ Sun Jul 23, 2006 10:18 pm ]
Post subject: 

Your first comment is utterly unnecessary. From the code (if the entire file were shown) it is easy to ascertain the type of "frame" and the arguments passed to add. It then becomes easy to determine what these methods do by looking at the documentation.

Further, any programmer with any decent level of Java GUI experience will not even need to consult the docs to figure that out.

If you wish to document what topPane and company are for, you should do that when you declare those variables.

Perhaps you should also name those variables to indicate what they are for, rather than where they will be placed.

Author:  Aziz [ Mon Jul 24, 2006 8:03 am ]
Post subject: 

Smile You make good points, wtd. In fact, I have started naming the panels by use. such as clockPane, listPane, etc. I like your way of thinking. I'm still use to commenting *everything* from my compsci class.

Author:  the_short1 [ Mon Jul 24, 2006 6:54 pm ]
Post subject: 

Aziz wrote:
Smile You make good points, wtd. In fact, I have started naming the panels by use. such as clockPane, listPane, etc. I like your way of thinking. I'm still use to commenting *everything* from my compsci class.


Yea, ditto on that one, im used to commenting practically everyline, it became habbit as i type a line of code type the comment after it.. and before line comments would double the length of the code so i always used trailling..

The convention for commenting, putting a /* Comment */ the line before/first line inside any if statement/for loop/method etc if needed, im finding is much more clearer, and neater then trailing comments.

Wtd, you mentioned comment it where you declared it, well im curious to the form that YOU use for commenting variables at the top of your code.

Java Convention mentioned if trailling comments are used, to align them with other variables. or at least keep the majority of them together.

eg:
int counter = 0; - - - - - - - - - - - // Counter for array filling
int thatOtherLongVariable = 0; // Im a useless variable

Do you think it would be better to initialize on a seperate line to avoid mess>?

Edit: dashes just used to keep the spaces there

Author:  wtd [ Mon Jul 24, 2006 10:06 pm ]
Post subject: 

code:
int counter = 0; // Counter for array filling
int thatOtherLongVariable = 0; // Im a useless variable


Place those comments above the code they relate to.


: