Programming Style

The place to hang out and talk about totally anything general.
User avatar
zach
level5
level5
Posts: 1350
Joined: Wed Jun 30, 2004 1:21 pm
Location: Denmarkia
Contact:

Programming Style

Postby zach » Tue Jul 22, 2008 9:41 am

Right. A lot here are coders, I know.

So, I figured I'd start a discussion on coding style. Now, I would have made this into a poll, but there's simply too many independent choices one can make when committing to a coding style, be it self-enforced or through some sort of prewritten guidelines - variable notation, indendation, brackets, number notation etc.

Personally, I've found my own style has evolved drastically over the past few years - less and less with time, as I become more confident in what I do and why I do it. I later found a style guide that fit most of how I already it, apart from a few things (like pointer *'s, and switch case colon whitespace).

Without further ado, a fictional snippet of C++ code as I would write it - disregard the contents, as the style is all that matters in this discussion.
I'm including ternary operators for fun and giggles, Byron.

Code: Select all

#ifndef MAIN_C
#define MAIN_C

#define PI       (3.14159f)
#define DEG(rad) ((float)rad * (360.0f / (2.0f * PI)))

#include <cstdio>
#include "glbase.h"
#include "main.h"



enum IntroversionGames {
        UPLINK,
        DARWINIA,
        DEFCON,
        MULTIWINIA,
        SUBVERSION,
        CHRONOMETER,
        GAMES,
};



class Trout {
        public:
                void smash();
                int getSmashes();
       
        private:
                bool smashed_;
                int smashes_;
};

Trout trout;



// main rendering loop
void draw(int width, int height) {

        // determine colour based on mouse button(s) pressed
        glColor3f(mouse.right  ? 0.5f  : 0.25f,
                  mouse.left   ? 0.5f  : 0.25f,
                  mouse.middle ? 0.75f : 0.375f);
       
       
        // print number of smashed trout, only if this trout is smashed
        // else a nonsensical statement involving plankton is printed
        if (trout == smashed) {
                int trouts = trout.getSmashes();
                int notUsed;
               
                printf("%d %s(s) %s\n", trouts, "trout", "smashed");
       
        // print nonsensical statement involving plankton
        // also do some redundant calculations
        } else {
                float x;
                float y = 1.0f;
                float *z = &x;
               
                x = y + (float)trout.getSmashes();
               
                printf("NONSENSICAL STATEMENT INVOLVING PLANKTON");
        }
       
       
        // the game! is it out?
        switch (game) {
                case SUBVERSION:
                        // fallthrough
                case CHRONOMETER:
                        printf("COMING ... SOMETIME!\n");
                        break;
                       
                case MULTIWINIA:
                        printf("COMING SOON!\n");
                        break;
               
                case UPLINK:
                        // fallthrough
                case DEFCON:
                        // fallthrough
                case DARWINIA:
                        printf("ALREADY OUT!\n");
        }
}

#endif /* MAIN_C */


Now, I really wish the bbcode [code] had syntax highlighting. Oh well, it's pasted here. I'll discuss my choices a little later in the thread, if it kicks off.

Discuss. (Obviously)
User avatar
LordSturm
level4
level4
Posts: 562
Joined: Mon Oct 02, 2006 5:13 am
Location: Australia - No Nukes :(
Contact:

Postby LordSturm » Tue Jul 22, 2008 10:18 am

SPARE THE POOR LITTLE TROUTS!

jelco the galactaboy wrote:The one thing I can't stand in many code snippets and I'm seeing in your sample as well is inconsistent brackets placement.

Code: Select all

How you do it:

clause {

} else {

}



How I do it:

clause
{

}
else
{

}


The worst language I've ever stumbled across is mIRCscript which forces you to use the first layout (and has some other tedious syntax requirements which I will not dig into too deeply for the sanity of us all).

The reason I do it this way is that it makes it a lot easier to see which bracket matches which. And of course you can just look at the first line at the same indentation level, and yes it save another few lines, but I'd like some clear overview and that is not the way I would achieve that. Moving on, I use indentation at every new curly bracket clause, and sometimes when it looks better for aestethics (in your example you did this with glColor3f()). Lastly I should note that I'm mostly a PHP programmer and it might be that some other languages would look nicer with other styles than I'm currently using. But at least I've abandoned my in-line HTML style which I used to use. :D

Jelco


The first one is proper style where as the second is "easier for the beginner." ( Not calling you a beginner, just pointing out why you might prefer it. )
How do you differentiate two ifs with an if then an else clause? As long as indentation is correctly used, all is well....

Also mIRC script does not force you to comply to that format, just some derivative of that and they supply a format correcting button.
After all it's just a script. :\
Last edited by LordSturm on Tue Jul 22, 2008 10:22 am, edited 1 time in total.
"Surely you didn't mean to press that button just then did you?"
"No, nor will i disarm the nukes."
"Oh well, I will have my Fighters shoot them down."
"Sure you will."
"Oh NOES, ITS BEEN PATCHED!!!"
User avatar
zach
level5
level5
Posts: 1350
Joined: Wed Jun 30, 2004 1:21 pm
Location: Denmarkia
Contact:

Postby zach » Tue Jul 22, 2008 10:21 am

Well, I think I am very thoroughly consistent throughout my code - I can see why you'd get used to having the bracket on a line by itself, though.

As you can probably see, I have heavy (8 character) indendation, so quickly figuring out which bracket belongs to what is pretty easy, especially considering that I (of course, as you) indent inside every bracket.

I suppose it depends a bit on your level of indendation. I have seen a lot of two-character indendation lately, and while I would actually like to like this style, I simply cannot. It relies more heavily on symbols to give an overview than what is actually possible in the language.
I can read my way through 4-character-indents, but I do much prefer 8-characters.
Yes, I still stick to 79 characters per line.

- and inline HTML is terrible, just as constant values apart from 0, 1, and (in a few cases) 2 - littered around the code. I know I put a 5 in there, though.

-----

I should mention that for single line statements, I do this:

Code: Select all

if (something)
        doNothing();
else
        doSomething();


- unless one of them is multiline, in which case the other(s) get brackets as well, at no additional cost:

Code: Select all

if (something) {
        doNothing();
} else {
        doSomething();
        crash();
}
Last edited by zach on Tue Jul 22, 2008 10:27 am, edited 1 time in total.
User avatar
LordSturm
level4
level4
Posts: 562
Joined: Mon Oct 02, 2006 5:13 am
Location: Australia - No Nukes :(
Contact:

Postby LordSturm » Tue Jul 22, 2008 10:23 am

Yeah, I use a TAB to indent, as long as it's constant throughout.
"Surely you didn't mean to press that button just then did you?"

"No, nor will i disarm the nukes."

"Oh well, I will have my Fighters shoot them down."

"Sure you will."

"Oh NOES, ITS BEEN PATCHED!!!"
User avatar
zach
level5
level5
Posts: 1350
Joined: Wed Jun 30, 2004 1:21 pm
Location: Denmarkia
Contact:

Postby zach » Tue Jul 22, 2008 10:29 am

TAB is variable width. Bitwise however, I use tab, with my editor set to 8 characters (of course).

If I post it somewhere, I convert the tabs to spaces - since with spaces instead of tabs, your layout won't be ruined as such:

Code: Select all

        glColor3f(mouse.right  ? 0.5f  : 0.25f,
                  mouse.left   ? 0.5f  : 0.25f,
                  mouse.middle ? 0.75f : 0.375f);


vs

Code: Select all

    glColor3f(mouse.right  ? 0.5f  : 0.25f,
          mouse.left   ? 0.5f  : 0.25f,
          mouse.middle ? 0.75f : 0.375f);


I never use TAB in other places than at the beginning of a line, though.
User avatar
NeoThermic
Introversion Staff
Introversion Staff
Posts: 6256
Joined: Sat Mar 02, 2002 10:55 am
Location: ::1
Contact:

Postby NeoThermic » Tue Jul 22, 2008 10:35 am

The programming style I use depends on what I'm doing. If I'm editing someone else's files, I'll use the style they used. If I'm starting my own code, I'll use the 'braces on their own lines' style. There's a few other things I'll do as well in the name of readability and defensive programming:

Code: Select all


if(x==y && z==7)

should be:

if ( x == y && z == 7 )


Spaces help the readability.


if ( x == SOMECONSTANT)

should be:

if ( SOMECONSTANT == x )

so that if you accidentally forget a '=' (everyone will do it at one point in a project), you get a compile time error rather than strange behaviour.

if ( x = y )
   dostuff();
else
   dosomething();


should just be banned from the face of the earth. Use braces even if you've only got one line in the statement:

if ( x = y )
{
   dostuff();
}
else
{
   dosomething();
}

(or for you one true brace peeps:)
if ( x = y ) {
   dostuff();
} else {
   dosomething();
}



That about sums me up.

NeoThermic
elDiablo
level5
level5
Posts: 3111
Joined: Thu Mar 14, 2002 12:23 pm
Location: London, UK

Postby elDiablo » Tue Jul 22, 2008 10:36 am

Multi-line if statements (even if other branches are single line):

Code: Select all

if( condition )
{
    DoSomething()
}
else if( something )
{
    DoSomethingElse();
}


Single-line if statements:

Code: Select all

if( condition )      DoSomething();
else if( something ) DoSomethingElse();
User avatar
multimania
level2
level2
Posts: 130
Joined: Fri Nov 26, 2004 4:07 pm
Location: Perth, Western Australia · Mountain View, California
Contact:

Postby multimania » Tue Jul 22, 2008 10:40 am

NeoThermic wrote:if ( x = y )
dostuff();
else
dosomething();


should just be banned from the face of the earth.[/code]


Is that because "if (x = y)" isn't nearly as useful as "if (x == y)"?
elDiablo
level5
level5
Posts: 3111
Joined: Thu Mar 14, 2002 12:23 pm
Location: London, UK

Postby elDiablo » Tue Jul 22, 2008 10:44 am

I use assignments in if statements all the time, though usually with function calls and not variables! Though assigning y to x, and then checking if x is non-zero in a single statement can (sometimes (maybe (kinda))) be useful... Still

Code: Select all

if( x = GetXValue() )
is nice!
We dont stop playing cos we get old... We get old cos we stop playing.
User avatar
NeoThermic
Introversion Staff
Introversion Staff
Posts: 6256
Joined: Sat Mar 02, 2002 10:55 am
Location: ::1
Contact:

Postby NeoThermic » Tue Jul 22, 2008 10:47 am

elDiablo wrote:Single-line if statements:

Code: Select all

if( condition )      DoSomething();
else if( something ) DoSomethingElse();


BURN!

I really don't get why people do that. Basically what happens if you come back to add more lines of code and are lazy and don't add the braces? You end up with spaghetti code. Best add the braces now, as then you can alter as required later.

NeoThermic
User avatar
KingAl
level5
level5
Posts: 4138
Joined: Sun Sep 10, 2006 7:42 am

Postby KingAl » Tue Jul 22, 2008 10:48 am

LordSturm wrote:The first one is proper style where as the second is "easier for the beginner." ( Not calling you a beginner, just pointing out why you might prefer it. )


Who made you the arbiter of 'proper style'? There's no general consensus on the matter.

I generally place the opening bracket on the same line as the rest of the opening syntax, but don't like tying an else to the closing bracket of the associated if. I generally place single statement if clauses on a single line, but I think the newline + indent approach is purdy. Everything else I'd pretty much agree with.

Not such a fan of macros doing what inlines and constants can do better, though.
Gentlemen, you can't fight in here: this is the War Room!
Ultimate Uplink Guide
Latest Patch
User avatar
NeoThermic
Introversion Staff
Introversion Staff
Posts: 6256
Joined: Sat Mar 02, 2002 10:55 am
Location: ::1
Contact:

Postby NeoThermic » Tue Jul 22, 2008 10:48 am

multimania wrote:
NeoThermic wrote:if ( x = y )
dostuff();
else
dosomething();


should just be banned from the face of the earth.[/code]


Is that because "if (x = y)" isn't nearly as useful as "if (x == y)"?


This is why I try do defensive programming!

NeoThermic
User avatar
zach
level5
level5
Posts: 1350
Joined: Wed Jun 30, 2004 1:21 pm
Location: Denmarkia
Contact:

Postby zach » Tue Jul 22, 2008 10:51 am

elDiablo wrote:

Code: Select all

if( x = GetXValue() )
is nice!


I'd argue that you should want to write that as

Code: Select all

if( x = GetXValue() != 0)

or

Code: Select all

if( (x = GetXValue()) != 0)

to avoid confusion between = and == - and further emphasise that one is an assignment.

-

NeoThermic, about the banning from the face of the earth, how about something like this?

Code: Select all

/* determine what kind of drawing should be performed */
if      (f[i].v[3]) glBegin(GL_QUADS    );
else if (f[i].v[2]) glBegin(GL_TRIANGLES);
else if (f[i].v[1]) glBegin(GL_LINES    );
else if (f[i].v[0]) glBegin(GL_POINTS   );

I suppose you could put brackets in there and still have them be oneliners, though.

NeoThermic, quoted freely, wrote:

Code: Select all

if ( SOMECONSTANT == x )

so that if you accidentally forget a '=' (everyone will do it at one point in a project), you get a compile time error rather than strange behaviour.

Now this I can see the point of! I've never thought of that before, and that is quite a brilliant way to do it.
However, I am concerned about readability.

Consider

Code: Select all

if (CROSSED_THE_ROAD == kitten)

just doesn't ... meh. I am a proponent of readable, self-explanatory code where applicable.

-----

EDIT:
NeoThermic wrote:Basically what happens if you come back to add more lines of code and are lazy and don't add the braces?


You aren't lazy like that. If one of them needs a bracket, they all get. Either that, or you're just begging for spaghetti code (in my opinion, brackets already look like pieces of spaghetti :P)
Last edited by zach on Tue Jul 22, 2008 10:55 am, edited 2 times in total.
User avatar
The GoldFish
level5
level5
Posts: 3961
Joined: Fri Mar 01, 2002 9:01 pm
Location: Bowl / South UK
Contact:

Postby The GoldFish » Tue Jul 22, 2008 10:53 am

Code: Select all

if ( x = y )
   dostuff();
else
   dosomething();


Why do correctly indented single line clauses require {}s? If it's indented correctly it's 100% readable as far as I'm concerned - what is the benefit in adding the brackets?
User avatar
bert_the_turtle
level5
level5
Posts: 4795
Joined: Fri Oct 13, 2006 6:11 pm
Location: Cologne
Contact:

Postby bert_the_turtle » Tue Jul 22, 2008 10:54 am

Use Python, then you don't have to argue about indentation and braces :) [/troll]

Braces on individual lines for me (did the other thing, but it makes it harder to scan where the statement opening a block is), spaces around operators and parentheses, no tabs (because every editor has a different idea how wide they're supposed to be), and function names starting with uppercase letters.

Oh, and on "if ( x == CONSTANT )": it's more natural to read in that form IMHO, and I usually use maximal warning + warnings are errors compilation options.
Last edited by bert_the_turtle on Tue Jul 22, 2008 10:56 am, edited 1 time in total.

Return to “Introversion Lounge”

Who is online

Users browsing this forum: No registered users and 43 guests