Skip to main content
GameDev.net gamedev.net
🔒 Locked

Popular coding style?

Started by Grahf750 Aug 19, 2006 at 5:33 PM 53 replies 8.9k views
Original Post
Grahf750
Grahf750
95% of the code I see has code that looks like this:

public void doesSomething(int x){
    if (x == 0){
	// stuff
    }
    else{
	//other stuff
    }  
}



When learning to code I learned to do it like this:

public void doesSomething(int x)
{
    if (x == 0)
    {
	// stuff
    }
    else
    {
	//other stuff
    }  
}



The way I learned seems much more readable to me with the brackets lining up. It also makes it easy to debug when your missing a curly brace. The problem is that when looking at the first example it takes me longer to understand and grasp it then the second because I am less familiar with it. I am wondering should I switch now to the first example because almost everybody else uses it and I will waste a lot of time trying to understand things simply because of my different format? Also I know jobs have certain requirements for the way things should be coded. Would something like this part of those requirements?
Driv3MeFar
Driv3MeFar
I personally use the second style, because its what I learned in originally. Honestly, once you've looked at enough code its easy enough to read either style. I would program in whatever you're most comfortable with, unless you're working with a team who all strictly adhear to the first style.
kordova
kordova
I would just choose a format that works for you and is sensical and stick with it. I have come across a ton of styles, all of which are "the best," and none of which fit just right with me.

Personally, my style adjusts over time as my experience dictates what is more readable and easy to type.

I would have written it:
public void doesSomething( int x ) {  if ( x ) {    // other stuff  }  else {    // stuff  }  }
Way Walker
Way Walker
My advice is to be flexible. Learn to read code that's in any half-way reasonable coding style. If you have trouble reading other styles, you'll lose out on a lot of resources. Also, be willing to change your style to match the requirements of your project.

I code in:
1) The style laid out in the project's guidelines
2) Failing (1), the style in which the majority of the code is already written
3) Failing (2), the style of the dominant libraries in the project (not really applicable when discussing bracing style)
4) Failing (3), roughly the first style you listed (it's my personal preference)

I probably would have written it:
public void doesSomething(int x) {    if (x) {        // stuff    } else {        // other stuff    }}

I rely strongly on indentation to clarify scope.

EDIT: Removed quote, it wasn't need
DeadXorAlive
DeadXorAlive
The second example is more readable to me, the first looks like a lot of effort is taken to save as much space as possible. Only sometimes I make an exception for single statements and if statements, like:

for (int i= 0; i < 10; ++i)    if this and that related to i        do something with i;

If it's a really whacky style to read, there are source code beautifiers, like uncrustify

Telastyn
Telastyn
Meh. Personally, I prefer brace after keyword:
public void doesSomething(int x) {    if (x) {        // stuff    } else {        // other stuff    }}


Always bracing after ifs. It's not really that big a deal though. If you're using VS2005 (and likely others), you can specify your own preferences and the IDE will reformat others' style into your own (and then back to the company standard).
Sol462
Sol462
I like to use a hybrid of the first and second methods, unless my supervisor makes me use the first. Sometimes I use the second if I need to see the brackets' alignment.

public void function(int x){    if (x == 0){        //stuff    }    else{        //stuff    }}
AbandonedAccount
AbandonedAccount
I found a very good reason to abandon the second style after a bit of experience, and that was due to misreading code. Let me explain:

A new scope {} can be created anywhere. I did not know that. So I saw code similar to this:
x=0;if (cond) x=1;//skip first element{  for (;x<10;x++)    //something done here}


I misread this as conditionally executing the for loop, while it was actually conditionally skipping a single iteration. Sure I could have blamed the person that wrote the code, but instead I switched styles and aimed to be able to read all code no matter how much I disagree with the style.

Shortly afterwards I was on a project which had a practice of commenting every ending-brace with what it corresponded to. This made the transition easier.

Most people I have encountered had an easier time learning with the second style, but everyone seems to eventually move to the first. I doubt it's always for the same reason I did, so maybe it's more information fitting on a single screen/page or just people adapting to the norm.
Conner McCloud
Conner McCloud
Quote:
Original post by richardurich
...

You didn't misread the code, the original author miswrote it. Changing styles won't do a thing to prevent such misunderstandings.

CM
Deyja
Deyja
Quote:
but everyone seems to eventually move to the first


I beg to differ. I used to do it the first way; now I do it the second way. And though I can certainly read both styles fine, I much prefer the second.
Limitz
Limitz
In my code you may find things like:
//C
int getSomeElement(){  int i; for (i=0;i<10;i++)  {    if (i==5) return i;  }}


i use scopes in my cases for switch also

//C#
switch (i){  case 0:  {    ArrayList al = Database.Query("select * from mytable1");    foreach (object[] obj in al) {}    break;  }  case 1:  {    ArrayList al = Database.Query("select * from mytable2");    foreach (object[] obj in al) {}    break;  }}

To show i can now use the same variable in multiple cases...
Limitz
Limitz
Quote:
Original post by richardurich
Most people I have encountered had an easier time learning with the second style, but everyone seems to eventually move to the first. I doubt it's always for the same reason I did, so maybe it's more information fitting on a single screen/page or just people adapting to the norm.


I actually started out with the second style, then moved to the first style for the same reason as you. But i recently went back to the second again. I trained myself to type the closing bracket of the scope first before writing the internals. I start like:
public void DoSomething(){}

and then i move on:
public void DoSomething(){  ArrayList al = GetMeAFancyList();  foreach (object item in al)  {  }}

now fill in the code of the foreach scope.
It helps me when i go many levels deep while writing lots of code (i had to do some calculations over a 9 dimension array once). Because before i did this i found myself ending my function with a load of closing brackets hoping for the best :)

Greetings.
jbadams
jbadams
I use the first style when coding in Java or C++, and the second when coding in C. It's just the way I was taught each and I don't really have trouble reading either, so I didn't feel the need to deviate from the style I was originally shown. I do like Python's no-brace syntax though.

As for changing your own coding style, I wouldn't recommend it unless you're doing so to meet a team or company standard. Just use whichever you feel comfortable with and make sure you're consistent. Each method is quite popular and will generally be fairly easy for most programmers to understand.
- Jason Astle-Adams
dcosborn
dcosborn
style #1 is good for its tendency to properly bind things together. Notice how the else statement tightly binds the two potential blocks together.
void doesSomething(int x) {    if (x) {        // stuff    } else {        // stuff    }}
With style #1, do/while loops are tightly integrated with the block structure.
void doesSomething(int x) {    do {        // stuff    } while (--x > 0);}
Under style #2, it becomes difficult to differentiate a do/while loop from an empty while loop; the integration is much looser.
void doesSomething(int x) {    do    {        // stuff    }    while (--x > 0);}
The same problem comes up with for loops, as richardurich mentioned. Under style #2, if you remove the for line, the code will remain meaningful, but with a different meaning. The code is written as if the for line were a sibling of the brace line while, as far as the meaning is concerned, they basically the same. Actually, the brace takes the place of the single expression after the conditional to create the multi-expression block, so it should either be indented or placed on the same line.
void doesSomething(int x){    for (int i; i < x; ++i) x--;    {        int x;        // stuff    }}
Orphaned scopes can be useful for avoiding pollution. With style #1, they are easy to recognize. Under style #2, they could easily be mistaken for a loop, as in the previous example.

However, single expressions after conditionals (is there a correct word for these?) are harder to recognize under style #1, especially if the conditional is really long.
void doesSomething(int x) {    if (x != 1 && ...) // pretend this conditional extends out of view        x = 0;    if (x != 1 && ...) { // pretend this conditional extends out of view        x = 0;    } // your only clue is the closing brace}


[Edited by - dcosborn on August 20, 2006 1:03:27 PM]
DeusFacticius
DeusFacticius
in my opinion, the first style just looks cluttered and a little less easily understood. i really dont know where that style came around from, i had never seen it until i started programming in Java, and even then it wasn't the way it was taught in my school.

it makes me think that it was possibly an adaptation of style from another language like visual basic, where code always starts on the next line, except for END statements (analgous to a closing bracket).
Captain P
Captain P
I use the second style at home, as I often use the bracelets to check scope. I always put an if statement code block on the next line to prevent the problem richardurich posted.
I use the first style at work, as it's the guideline I have to follow. It does result in shorter code and some may find that easier to read. It's not so bad now that I work with it, and although I still prefer the second style, I can see some reasons to use this one.

Yeah, it's just personal preference, or corporate guidelines. :)
Enselic
Enselic
Am I the only one using this hybrid?
public void doesSomething(int x){    if (x == 0) {	// stuff    } else {	//other stuff    }}

This way it is a layout-wise difference between structure (functions) and logic (if while do for etc) which I think makes the code easier to read.
Sol462
Sol462
Quote:
Original post by Enselic
Am I the only one using this hybrid?
*** Source Snippet Removed ***
This way it is a layout-wise difference between structure (functions) and logic (if while do for etc) which I think makes the code easier to read.


I usually use that one.

rip-off
rip-off
Quote:
Original post by Enselic
Am I the only one using this hybrid?
*** Source Snippet Removed ***
This way it is a layout-wise difference between structure (functions) and logic (if while do for etc) which I think makes the code easier to read.


I used to, but then I switched to something akin to the OPs #2.
JasonBlochowiak
JasonBlochowiak
Keeping the brace on the control line made a lot more sense when we had smaller monitors. Now, though, I would argue that the second style is more useful. Why? I think it matches the language structure better. For control structures, you have:

control    body//// thus:if (foo)    bar;//// or:if (foo){    bar;    baz;}//// Also, doingif (foo) {    bar;    baz;}//// is likely going to cost you more keystrokes to modify.// The only other really defensible (aside from "this is the // way I like it/got used to it") style would be:if (foo)    {    bar;    baz;    }


but I find that aesthetically less pleasing, and I tend to associate the braces with the control structure more than the controlled code.

Consistency is more important than anything, though, and if you're in a team environment, adherence to the group's style is more important to your career than your personal preferences are. :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.