Coding standards for Blocks of code - why do people use the bad one!

He has: 7 posts

Joined: Nov 2006

Hi
I am intersted to find out why, when it comes to the brackets in your blocks of code, do most people put the opening bracket on the first line of the block, and not start a new line, when clearly starting a new line is far better due to allowing easier identification of the blocks.

Example:-

Bad:-

if(x == y) {
    actions();
}
'

Good:-

if(x == y)
{
    actions();
}
'

So if there are many nested blocks of code you can always easily see the opening and closing brackets of the block for the second one above, but you cannot easily fo it for the first.

So why do people do it? I use Open Source software and when it comes to customisation its a nightmare trying to sort it all out. It drives me nuts!!

I am now using Notepad++ so it does identify matching brackets but you still have to scroll up/down loads of times to spot the matching bracket rather than just see it lines up in the same column.

Here's one site that states you must use second one above for PHP, although I am not sure who should set the standards on this? http://www.evolt.org/article/PHP_coding_guidelines/18/60247/

Cheers

Laurie

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

Good topic. Let's see if we can discuss this without triggering a holy war. Smiling

infocom wrote: So why do people do it?

Because they can. Smiling If there's more than one way to do something, someone will do it differently. I think people tend to read code the way they read natural language as much as possible, so wherever there's room for ambiguity there's bound to be inconsistency.

With the explosion in the number of languages over the last few decades, there has been plenty of room for variation and cross-pollination of syntax/style ideas.

It perpetuates for all sorts of reasons, too. For example, to deal with non-uniformity, many organisations who develop or maintain software have their own internal coding standards. Sometimes this aids consistency, other times it creates fragmentation.

infocom wrote: Here's one site that states you must use second one above for PHP, although I am not sure who should set the standards on this? http://www.evolt.org/article/PHP_cod...ines/18/60247/

Usually the people who design a language can say with some authority, for their language, what is good style and what isn't. If there is a canonical implementation, central module repository, or official editor, then coding standards could be applied to them. Outside of that, style is hard to enforce, though.

Some other standards and guidelines:
PHP PEAR coding standards
Java code convention
Python style guidelines (PEP Cool
Lisp programming style
GNU C coding standards

PHP is ragged with regard to coding standards. Everyone has their own style and I doubt it will be consolidated anytime soon, if ever -- a bit like C. The language specification is itself inconsistent and morphs rapidly, so it is problematic. I don't even encounter PEAR style much in the wild. I myself use a Java-like style, as I'm used to it and PHP's surface syntax looks similar to Java's (moreso with v5's OO system).

Parenthesised notations like Lisp's and XML's are easy to switch between styles. I use nXml mode in Emacs, with 2-space indentation, to edit XML/XHTML code. Though I've only done so for about a year, it's able to parse and update the layout of my older code, including SGML, seamlessly.

Lisp's style is interesting to consider because although the language is nearly 50 years old, there are multiple language specifications, and no canonical implementations exist, still most Lispers use almost exactly the same style. Partly, this is because Lisp is mature and has had time to establish conventions: literature, editors (esp. Emacs) and teachers are consistent. And partly, the style is basically self-evident due to its natural syntax.

Python is also curious as its indentation whitespace conventions are enforced by specification. Yet programmers can be inconsistent about which whitespace characters they use, internal whitespace and various other things as addressen in PEP8.

I use GNU C style solely for C, although I don't like it much. I prefer Allman style braces to either GNU or K&R. Like you said, coding standards vary a lot among free software, so I chose to stick to GNU style where possible as I figure that body of code will be around a long time. But sometimes when I inherit code, I adapt to whatever style the authors used.

Conventions are not easy. Ultimately, one tries to be consistent and somewhat dogmatic with code in close proximity, and pragmatic with code from afar. Smiling

He has: 1,758 posts

Joined: Jul 2002

What's bad about the first method? I use it all the time and I can read it just fine. The only reason I code in that style is because all of the books I learnt from show that style. I work with a lot of developers and only one of them uses the second method.

Andy

He has: 7 posts

Joined: Nov 2006

Hi Andy

Its bad because when someone who does not know the code that has been written, and there are many nested blocks, it can be very difficult for them to figure out where the blocks of code are.

Here's an example I recently worked on from Zencart with just 3 levels of nested blocks, and this is leading Open Source eCommerce software. Notice how in the second code you can instantly identify all the blocks compared to the first. This is just one small snippet, there are many more much larger blocks of code that you can spend hours in trying to sort it all out:-

Example Original Inline braces:

if ($products_options->fields['options_values_price'] != '0' and ($products_options->fields['product_attribute_is_free'] != '1' and $product_info->fields['product_is_free'] != '1')) {
                      // show sale maker discount if a percentage
                      $products_options_display_price= '' . $products_options->fields['price_prefix'] .
                      $currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . '';
                    } else {
                      // if product_is_free and product_attribute_is_free
                      if ($products_options->fields['product_attribute_is_free'] == '1' and $product_info->fields['product_is_free'] == '1') {
                        $products_options_display_price= TEXT_ATTRIBUTES_PRICE_WAS . $products_options->fields['price_prefix'] .
                        $currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . TEXT_ATTRIBUTE_IS_FREE;
                      } else {
                        // normal price
                        if ($new_attributes_price == 0) {
                          $products_options_display_price= '';
                        } else {
                          $products_options_display_price= '' .// $products_options->fields['price_prefix'] .
                          $currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . '';
                        }
                      }
                    }
'

Amended with good indentation and new line braces:

if ($products_options->fields['options_values_price'] != '0' and ($products_options->fields['product_attribute_is_free'] != '1' and $product_info->fields['product_is_free'] != '1'))
{
// show sale maker discount if a percentage
$products_options_display_price= '' . $products_options->fields['price_prefix'] .
$currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . '';
}
else
{
// if product_is_free and product_attribute_is_free
if ($products_options->fields['product_attribute_is_free'] == '1' and $product_info->fields['product_is_free'] == '1')
{
$products_options_display_price= TEXT_ATTRIBUTES_PRICE_WAS . $products_options->fields['price_prefix'] .
$currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . TEXT_ATTRIBUTE_IS_FREE;
}
else
{
// normal price
if ($new_attributes_price == 0)
{
$products_options_display_price= '';
}
else
{
$products_options_display_price= '' .// $products_options->fields['price_prefix'] .
$currencies->display_price($new_attributes_price, zen_get_tax_rate($product_info->fields['products_tax_class_id'])) . '';
}
}
}
'

He has: 7 posts

Joined: Nov 2006

Quote: I work with a lot of developers and only one of them uses the second method.

That's the problem!

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

While I usually use the second method, I think both are just fine as long as you stay consistant with the indentation. The example you gave, I could read both just fine (although on your "bad" xample, the first line's indentation didn't match the rest).

With so many good IDE's now for PHP, either method is easy to deug now. I like how Zend Studio will find matching brackets and highlight them. One really nice thing is say the if statement is scrolled off of the top of the screen, putting the cursor at the brackt, it will show the line for the matching bracket at the top so you can see what you are matching even though the code isn't on the screen Smiling

-Greg

He has: 1,758 posts

Joined: Jul 2002

That's what I was thinking. Usually after I put a line break or two before a new block so I can see it clearly i.e.

if($x == $y) {

    $thisblock = "different";

} else {

    $thisblock = "whatever";

}
'

Which I find to be just as clear.

Andy

He has: 7 posts

Joined: Nov 2006

Yeah, I use Notepad++ now and this also highlights the opening and closing brackets, but this doesn't help if it is off the screen. You have to do loads of scrolling. Perhaps I should try some other editors/IDEs. Any other you recommend?

I just think that if something can be done better, it should be. I dont see why a not so good a system should be used for old times sake, if a better one exists. I read somewhere the first style is a Unix based style so I think it must just have been around for some time and people just use the system they are familiar with.

Or does my bad example have advantages over the second? Perhaps I am missing something, but I just cant see why it should be used when the second one is more clear. I dont think because we have editors to identify blocks is a good enough reason for staying with it. Perhaps if everyone used the second example there would be no reason to develop editors to identify the blocks.

Similarly in stylesheets!

I hate this:-
#div { color: black; font-weight: bold; font-size: 10px; }'

Arrrgghhh!!

Why not this:-

#div
{
    color: black;
    font-weight: bold;
    font-size: 10px;
}
'

Its just easier to identify.

I wish there was a LAW and when something better came out everyone had to go and change their code to the better one ha ha!

Thanks for your replies! Smiling

He has: 1,758 posts

Joined: Jul 2002

lol... again I do:

#div {

    color: black;
    font-weight: bold;
    font-size: 10px;

}
'

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

I always do the opening brace on a separate line because it is easier to read. It seems that people prefer method #1 to save space, but I don't understand the point of saving space. Generally, the more spread out it is, the more easier it is to read. I have many organizational spaces in my code.

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

Your "bad" example is the K&R style. It comes from the Kernighan and Ritchie book The C Programming Language. It's good mainly because it doesn't waste a line for a single brace, which means you can fit more on the screen (or page) vertically -- to avoid "loads of scrolling". Note that the header is aligned with the closing brace; with sufficient visual emphasis (bold, colour) on the opening keyword, you won't need the brace on the next line to identify blocks.

Your "good" example is the Allman style. There are a few other popular ones, see the Wikipedia article on indent style.

Adding extra indentation can make K&R style equally readable. In fact, I think your second example is more readable for that reason. Use 8-space indents on the first and it will look much better. You padded the first snippet in a great deal extra too.

infocom wrote:
Perhaps I should try some other editors/IDEs. Any other you recommend?

I just think that if something can be done better, it should be. I dont see why a not so good a system should be used for old times sake, if a better one exists.

May I suggest Emacs? Smiling

infocom wrote: Perhaps if everyone used the second example there would be no reason to develop editors to identify the blocks.

No way, block-level editing is useful for many, many other reasons. Smiling

He has: 7 posts

Joined: Nov 2006

I will try Emacs. Think I tried it some time ago on linux. Always thought it was a *nix only system but can see on the link you gave its Windows too.

Perhaps its the indentation, or combination with, which makes it unreadable then. Perhaps better indentation would improve identifying the blocks using that style.

Pewrhaps I just need to get used to "spotting" the blocks. Maybe I am not used to it and that's why. Maybe its possible to train yourself to spot it better.

They have: 15 posts

Joined: Oct 2006

I find myself using the "bad" method most of the time. When I work on something with a friend of mine, I use the "good" method, just because that is what he uses.

All the scripting/programming books I've ever read say that the right way is the way the company you work for/with uses. If they say "do it this way," then you do it that way. Otherwise, do it how you feel comfortable. That's the glory of using languages where spacing doesn't matter.

As for an editor, I use Crimson for just about everything.

Relevancy is key! Get the most out of your keywords: http://www.olcore.com

He has: 7 posts

Joined: Nov 2006

I think if your company uses closed/proprietary software then yes you should use the company standards (which I think should be based on some standard).

But I think with Open Source there should be a common standard, and not individual standards that are preferable to the developer.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.