Coding style question

KimB

Legend
I'm just curious. It seems like the overwhelming majority of code that I look at uses the following convention:
Code:
function foo(float x) {
  if (x = 1) {
    //do stuff
  }
  else {
    //do other stuff
  }
}

But I've always thought that the following arrangement of the brackets was vastly more readable:
Code:
function foo(float x)
{
  if (x = 1)
  {
    //do stuff
  }
  else
  {
    //do other stuff
  }
}

So, the question is, if anybody here prefers the above format, is there any specific reason?
 
Both have their pros and cons.
The first example is more compact, which lets you see more of your code at once.

The second example makes it easier to locate matching braces as they will always be at the same level of indentation (this is the method I prefer).

In practice many companies have a standard style which all programmers are supposed to follow. This makes it easier for people to pick up someone elses code and follow it, as they don't have to cope with someones idiosyncratic coding style.

The first time I came across hungarian notation I thought it seemed cumbersome and a waste of time. After a short amount of time it becomes second nature and very useful.

CC
 
I do this
Code:
function foo( float x )
{
  if  ( x == 1 )
 {
    //do stuff
  } else {
    //do other stuff
  }
}
 
Chalnoth, I like your coding style infinitely better! People generally seem to use the other style for compactness, but in my opinion readability is far more important. It's also easier to type and change code when the braces are aligned, because you spend less time 'decyphering' your own code.

By the way, I think you intended to write the following (assuming C/C++/C#/Java):
Code:
if(x == 1)
And testing for exact equality of a float isn't commonly done either. ;)

Anyway, you might have noted that I prefer no space after the 'if'. I see no reason to add it. And it reminds me too much of Basic syntax IF x = 1 THEN.
 
I use exactly the same style as Chalnoth (including the spaces after the if - it's not a function call after all ;)).
 
Captain Chickenpants said:
The first example is more compact, which lets you see more of your code at once.
Yeah, but I think it stems from the time when 800x600 was considered high-resolution and we only had matrix printers. :D
The first time I came across hungarian notation I thought it seemed cumbersome and a waste of time. After a short amount of time it becomes second nature and very useful.
Would you mind explaining some of the advantages of Hungarian notation? I still find it cumbersome and a waste of time, and I feel lucky I haven't been forced to write it... But I'm open for different opinions.
 
[maven] said:
I use exactly the same style as Chalnoth (including the spaces after the if - it's not a function call after all ;)).
You can put whitespace between a function's name and its argument list as well. It's all valid syntax. But just like there's no clear point doing that for functions I don't see why I should do it for 'if'. Ok, you might argue that it discerns the two, but frankly I've never confused them. All compilers/editors have syntax coloring and 'if' isn't a valid function name. So, seriously, typing a space after 'if' looks to me like it's a habit from programmers who want C to look more like Basic. In Basic there's a space after function names as well...

Have a look at the following two 'while' loops:
Code:
while (true)
{
   // ...
};

while(true)
{
   // ...
};
Personally I find the first one looks like you wanted to write 'while true' but you end up with a 'true' enclosed by parenthesis floating into space. :D The second style clearly shows they belong together. And with syntax coloring and the simple fact that 'while' can't be a function name and the line isn't ended with a semicolon I see no reason for confusion. I mean, the first version could just as easily be mistaken for a function call... practically impossible for anyone with more than five minutes of C style programming.

But that's just my opinion of course.
 
Nick said:
Yeah, but I think it stems from the time when 800x600 was considered high-resolution and we only had matrix printers. :D

Would you mind explaining some of the advantages of Hungarian notation? I still find it cumbersome and a waste of time, and I feel lucky I haven't been forced to write it... But I'm open for different opinions.

The biggest advantage is when looking through other peoples code. You can tell from the variable name what the type of the variable is without having to go and find where it is defined. If you are using some of the other common conventions such as prefixing g_ before global variables, and m_ before C++ Class members then you can also see the scope of a variable.

as an example when you look at:
Code:
 pnIndex = 1;
It is obvious that something is wrong, as the hungariang notation here says that it is a pointer to an integer (pn) and setting a pointer to be 1 is not something you would normally do. What is probably meant is
Code:
 *pnIndex = 1;

Now if you weren't using hungarian notation you would probably use a variable name like IndexPointer but that ends up longer than the hungarian notation and is still ambiguous.

CC
 
Chalnoth said:
So, the question is, if anybody here prefers the above format, is there any specific reason?
The first option for me, but that's more habitual than by any coherent choice. Besides, the editor should take care of bracket matching anyway so that I don't have to... ;)
 
I never write functions which are complex enough to cause error in reading them.
If a function has enough stuff in it that it causes you and other people to make mistakes when reading it then your design is broken and you should fix it.

Check out the Doom 3 source code for examples of good functions which are very easy to read.
 
Nick said:
By the way, I think you intended to write the following (assuming C/C++/C#/Java):
Code:
if(x == 1)
And testing for exact equality of a float isn't commonly done either. ;)
Well, in that case I wouldn't have preceded the definition by "function" either :)

Anyway, the one thing that I do use float equality testing for is checking to see if a variable has been modified since a particular block of code last looked at it.
 
Nick said:
Would you mind explaining some of the advantages of Hungarian notation? I still find it cumbersome and a waste of time, and I feel lucky I haven't been forced to write it... But I'm open for different opinions.
Well, I haven't actually used it (in physics, I'm almost of off in my own little world as far as programming goes, so it's hard to keep disciplined, and nearly impossible to find readable code made by my peers), but I can see the advantages, even when writing my own code. I've made a number of mistakes in improperly dealing with types before, and something like this could help significantly.
 
K.I.L.E.R said:
I never write functions which are complex enough to cause error in reading them.
If a function has enough stuff in it that it causes you and other people to make mistakes when reading it then your design is broken and you should fix it.

Check out the Doom 3 source code for examples of good functions which are very easy to read.
Nonsense!
It is quite easy to make a mistake in even short bits of code.

There are no hard and fast rules about the right length of a function. It is completly dependant on the problem you are solving. Constructiung artificial partitions to seperate things into functions can make the program less readable and slow it down.


CC
 
K.I.L.E.R said:
I never write functions which are complex enough to cause error in reading them.
If a function has enough stuff in it that it causes you and other people to make mistakes when reading it then your design is broken and you should fix it.

Check out the Doom 3 source code for examples of good functions which are very easy to read.
My primary maxim when writing new code is to test it rigorously while it's still short. That makes it much more likely for any bug that I find in my code to be right in front of me, instead of off in some obscure file somewhere.

Unfortunately, many of my functions are very mathematical, and often won't be easy to read no matter what I do.
 
I came across some code a few weeks ago which seemed to use some sort of bizarre reverse-capitalisation for some of the variables names (they seemed mostly be to constants).

So rather than

Code:
SUBDIVISON_THRESHOLD
or even

Code:
SubdivisionThreshold
they'd written

Code:
sUBDIVISIONtHRESHOLD
I was quite gob-smacked. Granted, the code was written by half-a-dozen different people all with crazy Polish / Russian-sounding names, but I still wonder about the thought processes they must have gone through to decide that that was a good idea :???: This, you see, is the sort of brain-damage you get when you give astronomers access to a computer keyboard!
 
Captain Chickenpants said:
The second example makes it easier to locate matching braces as they will always be at the same level of indentation (this is the method I prefer).

Same (for the same reason), though I notice some languages use the final moustache as a return operator.
 
Regarding the OP, the opening brace on the same line has always been described to me as the "Java way" (accurate or not) whereas both braces on new lines in the same column is the "C/C++ way". Its purely religeous in my experience - people stick to what they like and tend to get all up-tight and unfriendly if you tell them its "wrong" :LOL:

As a random bit of trivia, the code I submitted for the DirectX SDK used formatting different to the standard samples. I was told it was fine, but that they would forward the hate mail directly to me :smile:. I chose to change it to their style!

Captain Chickenpants said:
There are no hard and fast rules about the right length of a function. It is completly dependant on the problem you are solving. Constructiung artificial partitions to seperate things into functions can make the program less readable and slow it down.
I've read quite a few software engineering books that do at least have guidelines as to the length of functions/procedures. I'm currently reading "Code Complete" and I'm pretty sure that had a chapter entirely about good design/layout.

Conversations: Hungarian wartHogs - Jim Hyslop and Herb Sutter is an interesting read regarding hungarian notation.

I personally dont like it a huge deal, but for some reason I instinctively end up doing some sort of half-baked hybrid version :oops:
 
Captain Chickenpants said:
Now if you weren't using hungarian notation you would probably use a variable name like IndexPointer but that ends up longer than the hungarian notation and is still ambiguous.
Hungarian notation makes almost all variable names longer, often needlessly...

Personally I just give variables a name that best reflects their type. Also, variables with a short scope get short names, while variables with long scope get long names. For example a loop counter almost never has to be longer than 'i' while a global variable from a different module could be written like 'otherModule::detailedGlobalVariableName'. Also, for object-oriented languages it doesn't make sense to use Hungarian notation for class names, which are often in the majority. Last but not least, in the 21'th century we have IDE's with coding assistance. I only have to hover my pointer over a variable to get its type, and a mouse click brings me to its declaration.

Anyway, what do you mean 'indexPointer' would be ambiguous?
 
Last edited by a moderator:
Nick said:
Hungarian notation makes almost all variable names longer, often needlessly...

Personally I just give variables a name that best reflects their type. Also, variables with a short scope get short names, while variabled with long scope get long names. For example a loop counter almost never has to be longer than 'i' while a global variable from a different module could be written like 'otherModule::detailedGlobalVariableName'. Also, for object-oriented languages it doesn't make sense to use Hungarian notation for class names, which are often in the majority. Last but not least, in the 21'th century we have IDE's with coding assistance. I only have to hover my pointer over a variable to get its type, and a mouse click brings me to its declaration.

Anyway, what do you mean 'indexPointer' would be ambiguous?

Well is it a pointer to a variable that is an index into something. Or is it being called IndexPointer because it is an an index that points to a particular element.
i.e. are you describing what the index is for, or what the type of it is?

Hungarian notation IS giving variables names that best reflect their type, in addition it is a convention that other programmers will be able to follow when looking at the code.

I don't tend to do much C++ so couldn't comment on the class names, but surely it is useful to know the types of the class members? In the end unless you build all of your classes on top of other classes you will be using basic types at some point, and to be able to differentiate them from the members that are other classes should be useful. For example knowing that you are adding two objects of a class rather than two integers means that you know that the addition operator may have been overloaded and the result may not be immediatly obvious (admittidly that would assume you overloaded the operator with something silly).

I am not sure that simply relying on the IDE to handle it is a great approach, if you are looking at a code snippet in isolation or are in an evironment without a decent IDE then suddenly you will find your reliance on the IDE telling you, to be a pain.

All that said, if you are working mostly on your own and always have a decent IDE then it will probably make little difference.

CC
 
JHoxley said:
Regarding the OP, the opening brace on the same line has always been described to me as the "Java way" (accurate or not) whereas both braces on new lines in the same column is the "C/C++ way". Its purely religeous in my experience - people stick to what they like and tend to get all up-tight and unfriendly if you tell them its "wrong" :LOL:

As a random bit of trivia, the code I submitted for the DirectX SDK used formatting different to the standard samples. I was told it was fine, but that they would forward the hate mail directly to me :smile:. I chose to change it to their style!

I've read quite a few software engineering books that do at least have guidelines as to the length of functions/procedures. I'm currently reading "Code Complete" and I'm pretty sure that had a chapter entirely about good design/layout.

Conversations: Hungarian wartHogs - Jim Hyslop and Herb Sutter is an interesting read regarding hungarian notation.

I personally dont like it a huge deal, but for some reason I instinctively end up doing some sort of half-baked hybrid version :oops:

The openning brace on the same line is the way the original K&R book did it, and as a result is and was used by many "older" C programmers.

The openning brace on a new line was used in all the C++ texts and I believe current K&R edditions do this to, so most newer C/C++ programmers use this convention.

I used the former for close to a decade before I went through the pain of switching to the latter.

A lot of people get religious on this issue, but in the end it doesn't much matter, pick one and stick to it, you'll have to deal with whatever is dicatated and probably both (if there is any legacy code or external code) in a real engineering environment anyway.

One of our coding standards is that you work in the style of the file that your working in, meaning you don't go reformatting brackets for no real reason because it makes merging changes in a file a pain in the ass.

I don't like Hungarian with exception of designating member/static and global variables. I can see some argument for pointers, but the rest is more about a lack of type checking in C compilers than it is about readability.
 
Back
Top