# about code style



## jronald (Mar 21, 2010)

I find almost all the source code of *nix take such a style:

```
for (...) {
  if () {
  }
}
```
instead of

```
for (...)
{
  if ()
  {
  }
}
```

But the latter is more clear, isn't it? It's symmetric.


----------



## tingo (Mar 21, 2010)

Welcome to unix-land! Prepare to have your tastes and styles altered!
Start with style(9). Good luck!


----------



## gcooper@ (Mar 21, 2010)

There really is no defacto standard, but there are similarities between projects as far as style is concerned. Take for indentation and bracing in FreeBSD against many FSF/GNU projects:

FreeBSD...


```
for (...) {
	/* This is a multiline for-loop */
	if (...) {
		/* This is a multiline if-statement */
	}
}
```

GNU...


```
for (...)
  {
    /* This is a multiline for-loop */
    if (...)
      {
        /* This is a multiline if-statement */
      }
  }
```

Hard to read, eh? Of course this example was oversimplified, but I think you get what I mean...


----------



## aragon (Mar 21, 2010)

jronald said:
			
		

> But the latter is more clear, isn't it? It's symmetric.


Not in my opinion.


----------



## Brandybuck (Mar 21, 2010)

jronald said:
			
		

> But the latter is more clear, isn't it? It's symmetric.


I use the former almost exclusively, unless the client requires something else. I never thought of it as being Unixy.


----------



## phoenix (Mar 22, 2010)

Code style is a personal decision.  Use whatever style you want for your own code.  If your projects become big and public, then you can impose whatever style guidelines you want.

So long as you are willing to adopt the coding style of whatever other projects you want to contribute code to.    There's nothing worse than someone coming out of the woodwork with a single patch saying, "This is the one try style, bow down before it, and re-write all of the exising code to match this one patch."


----------



## jronald (Mar 22, 2010)

phoenix said:
			
		

> Code style is a personal decision.  Use whatever style you want for your own code.  If your projects become big and public, then you can impose whatever style guidelines you want.
> 
> So long as you are willing to adopt the coding style of whatever other projects you want to contribute code to.    There's nothing worse than someone coming out of the woodwork with a single patch saying, "This is the one try style, bow down before it, and re-write all of the exising code to match this one patch."


I agree that code style is a personal choice. Although there can be different styles in one project, they are localized (in files), localizing is great. It's ok to read code in different styles, and think that it will help to improve the code style, and different styles for different codes sometimes. The problem is that almost all code are in one style nowadays.


----------



## gilinko (Mar 22, 2010)

I also use the former variant, mainly because the preferred coding standard by both Sun Java Code Conventions and for the Drupal CMS system Drupal Coding Standard.

However, my main reason for the user of the former is that it cuts down on the scrolling up and down the source code due to the "extra" lines. In the simple example there is two extra lines, and when the if/else/try/whachamacallit grows in numbers so does the length of the file in the editor.


----------



## jronald (Mar 22, 2010)

gilinko said:
			
		

> I also use the former variant, mainly because the preferred coding standard by both Sun Java Code Conventions and for the Drupal CMS system Drupal Coding Standard.
> 
> However, my main reason for the user of the former is that it cuts down on the scrolling up and down the source code due to the "extra" lines. In the simple example there is two extra lines, and when the if/else/try/whachamacallit grows in numbers so does the length of the file in the editor.


In this view, you are right.
In another view, after proper abstracting, a function should not be that large in most cases.
If a funtion is large, it can use the former style, or even a more compacted one.
So every function can have a style that suits.


----------



## Oxyd (Mar 22, 2010)

I mix the styles.


```
void foo() {
  ...
  if (bar) {
    ...
  }
  ...
}

// But
void baz(int lots, int of, int parameters, int so, int much,
         int it, int does, int not_fit, int on, int just,
         int one, int line)
{
  ...
  if (really && really && long
      && ugly && condition)
  {
    ...
  }
  ...
}
```
Yes, I differ from style(9).

This is another plus for Python.  You get almost no parens and braces there, so little style to argue about:
	
	



```
def foo():
  ...
  if bar:
    ...
  ...
```
Of course, then you get people whining that the syntax is nothing like C and that C-like syntax is the only true path to enlightenment.  People just _love_ arguing about syntax and style.


----------



## gilinko (Mar 22, 2010)

jronald said:
			
		

> In this view, you are right.
> In another view, after proper abstracting, a function should not be that large in most cases.
> If a funtion is large, it can use the former style, or even a more compacted one.
> So every function can have a style that suits.



Abstracting is always something to aim for, but even then in general(the source code that I usually work with) you have something like 10 functions per file. And if each of those functions have only one if clause(highly unusual) you will have an extra 20 lines. Using a more realistic number of 4-5 if/else/for/do etc per function you are quickly up to 100 extra lines and that's just not my cup of tea.

But the main thing I would say is to choose one that suit you and follow it to the letter. Mixing and matching only adds to confusion. That's one reason that I follow the drupal php standard even in non-drupal code, because it is controlled down to the naming of the variables, functions and arguments. And thus you easily known what a variable is. Also if get confused on how something should be structured, I can just look it up in the standards


----------



## rden (Mar 26, 2010)

Somewhat related, one of the ugliest incidents I cam across was a company where the sysadmin had everybodies tab size (in vi no less) to 3.
Was OK looking at source inside their shop, but the small indent encouraged their people into deeper nesting than normal, and looking at their code outside their environment was just plain ugly.  Worse was they had the audacity to complain my [fully standard] indenting was non standard.

Just goes to show there are often worse problems out there than lining up curly braces.

on the original topic for mine the second variant (open curly on it's own line) is just a waste of visible real estate - far more sensible to go the first way.


----------



## phoenix (Mar 26, 2010)

Personally, I prefer a hybrid:

```
while (true)
{   if (whatever = something)
    {    do_something;
    }
    else
    {    if (stuff = boring)
         {   do_something_else
             lots_of_somethings
         }
    }
}
```

Keeps the braces lined up so you can visually see the groupings, but doesn't waste as much space as putting them on their own lines.  And, depending on the text editor, I may indent the braces.

However, this is just my preferred indentation/brace-style, and not the basis for my religion.


----------



## SR_Ind (Apr 10, 2010)

phoenix said:
			
		

> Personally, I prefer a hybrid:
> 
> ```
> while (true)
> ...



Completely in agreement with you and that's also my style of coding.

Nowdays with 19 inch monitors becoming standard issue for development workstations, its much easier to accomodate braces on separate lines. The old arguement of scrolling up/down doesn't hold anymore. Code blocks are also easily discernable at a glance.

In fact there are whole bunch of so-called "style" or "guidelines" that were adopted to cope with 80x25 real-estate over slow terminals.


----------



## expl (Apr 11, 2010)

Where you place brackets does not matter much, what makes pain in my brain most of time are people using several spaces instead of a single tab when I need to patch or copy code between tabbed and spaced code I end up spending a lot of time converting spaces to tabs or vice versa.


----------



## ProFTP (Apr 11, 2010)

everything must writers on one line, otherwise we will go to Libya to protect the security of the USSR 


```
package qxp;
use strict;
sub H($){pack'H*',$_[0]}
sub by{map{[splice@_,1,$_[0]]}!($#_%$_[0])..$#_/$_[0]}
sub is($){$_ eq$_[0]}
sub cat{join'',@_}
sub list{@_}
sub wa{wantarray?@_:cat@_}
sub yuki(&@){shift->();@_}
sub fopen(;$){open my$z,$_[0]||$_;$z}{my %file;
sub file($){readline($file{$_[0]}||=fopen$_[0])}}
sub slurp(;$){wa map{yuki{close$_}<$_>}fopen$_[0]}
#sub spew($;$){sub{map{print $_ $_[1];close$_}fopen$_[0]}->($_[0],$#_?$_[1]:$_)}
sub spew($;$){open my$z,">$_[0]";print $z $#_?$_[1]:$_;close $z}
sub table{map{chomp;[split/\t/]}@_}
sub trim{map{s/^\s+|\s+$//g}@_?@_:$_}
sub count{my%z;$z{$_}++for@_;\%z}
sub uniq{keys%{count@_}}
sub copy{wa local@_=@_}
sub find(&@){no strict 'refs';local(*{(caller).'::a'})=\(my$a=$_[1]);&{$_[0]}||($a=$_)for(@_[2..$#_]);$a}
sub first(&@){$_[0]->()&&return$_ for@_[1..$#_]}
sub min{find{$a<$_}@_}
sub max{find{$a>$_}@_}
sub section{map{$_->[$_[0]]}@_[1..$#_]}
*#=sub{map$#$_,@_};
sub zip{map section($_,@_),0..max &#(@_)}
sub char{substr$#_?shift:$_,$_[0],1}
sub via(&$){local $_=$_[1];$_[0]->()}
*\=sub{map[section($_,@_)],0..max &#(@_)};
{my%ops;*?=sub{ref$_[-1]?map&?($_[0],@$_),&\(@_[1..$#_]):wa do{my@z=$_[1];@z=$ops{$_[0]}->($_,@z)for@_[2..$#_];@z}};
{no strict 'refs';(*$_,$ops{$_})=eval"sub{&?('$_',\@_)},sub{wa(\@_[1..\$#_]) $_ \$_[0]}" for qw'** =~ !~ * / % x + - . << >> < > <= >= lt gt 
le ge == != <=> eq ne cmp & | ^ && || .. ... = , => and or xor'}}
my%refs=(''=>'_',map{$_=>lc substr $_,0,1}qw{SCALAR ARRAY HASH CODE REF GLOB LVALUE});
sub refs{wa map{$refs{ref $_}||'o'}@_}
sub _{cat map{
  is '' ? $_:
  is 'a' ? @{$_[0]}:
  ()
}refs@_}
sub wday{(int(365.25*($_[2]-($_[1]<3)))+int(30.6*(1+$_[1]+12*($_[1]<3)))+$_[0]-621050)%7+1}
sub leap{$_[0]%4?0:$_[0]%100?1:$_[0]%400?0:1}
sub days{(31,(28+leap $_[1]),(31,30,31,30,31)x2)[$_[0]-1]}
sub cal{by 7,((undef)x(wday(1,@_)-1),1..days @_)}
sub all{@_==grep$_,@_}
sub one{1==grep$_,@_}
sub none{!grep$_,@_}
sub any{!&none}
sub import{no strict 'refs';*{caller(0)."::$_"}=${"$_[0]::"}{$_} for grep !/^(BEGIN|__ANON__|a|import)$/, keys%{"$_[0]::"}}
package www;
use strict;
use qxp;
use config;
use L2;
#use encoding 'utf8';
my $utf8=0;
sub import{no strict 'refs';do{*{caller(0)."::$_"}=${"$_[0]::"}{$_}} for qw'template html depercent';} # out! out!
my %template;
sub template;
#require tags;
*template=templator{copy $template{$_[0]}||=slurp "$path::templates/$_[0].htm"}
#    '<#','#>' => sub{package tags;eval$_[0]},
    '${','}'  => sub{$_[1]{$_[0]}},
    '<@','@>' => sub{template $_[0]},
    '<^','^>' => sub{$^{$_[0]}}
;
sub html;
*html=subst
    '&'=>'&',
    '<'=>'<'
;
sub depercent{map{s/%([\dA-Fa-f]{2})/pack 'C',hex $1/ge;utf8::decode $_ if $utf8;$_}@_}
sub ok{print template 'index'}
sub rf{
  $_[0]{url}||=$ENV{HTTP_REFERER};
  $_[0]{time}||=0;
  print template 'refresh',$_[0];
}
$ENV{PERL}=$];
$ENV{URL}=s,^/,,?[grep!/\W/,split'/']:[] for copy $ENV{REDIRECT_URL};
$ENV{QUERY}={depercent split/&|=/,$ENV{QUERY_STRING}};
$ENV{POST}={depercent split/&|=/,do{read STDIN, my $x, $ENV{CONTENT_LENGTH};$x}} if $ENV{REQUEST_METHOD} eq 'POST' and $ENV{CONTENT_TYPE} =~ 
'^application/';
$ENV{COOKIE}={split/; |=/,$ENV{HTTP_COOKIE}};
666;
```


----------



## rden (Apr 15, 2010)

expl said:
			
		

> Where you place brackets does not matter much, what makes pain in my brain most of time are people using several spaces instead of a single tab when I need to patch or copy code between tabbed and spaced code I end up spending a lot of time converting spaces to tabs or vice versa.



It's not their coding, just lousy text editors that don't automagically tabify sets of 8 leading spaces into tabs when saving the file.

Of course if you are like the weird place (like I described above) where they redefined the tab size [in vi] then it's your own fault (and a lot of public domain code will give you problems).


----------



## Ruler2112 (Apr 16, 2010)

Here's my coding style, which I personally think is the best out of all I've seen.  (Naturally.  )  Elements are borrowed from a multitude of different styles I've seen and worked on over the years.

At the top, right after the she-bang line, I have a block of comments that explain what the script does, any arguments to it, then the license (on the off-chance I post/release it).  Then I have a change log - includes the date, initials, description of each change.  I then have a variable declaration/setting section where all the variables that should be set to affect the behavior of the script are kept; these are usually commented.  After this is a stern warning to not change anything below unless you know what you're doing.

For the code itself, I like to put everything within each logical block on the same vertical plane and each plane level is indented 2 spaces from the last.  (I have the default tab width in vi set to 2, and set to convert tab characters to spaces.)  Each brace goes on it's own line, except in very rare circumstances where the entire function/condition/loop is only a single line.  (Even then, it's very unusual for me to not split out the braces.)  Each function or significant block of code is separated by a blank line.  If a function call needs to span lines, the first argument goes on the same line as the call and each argument goes on another line, indented so that it lines up with the start of the first one.  The closing ) goes on a line by itself, indented to the same level as the opening (.  Likewise with a multiple-line if statement, except that the closing ) is on the same line as the last condition.

I've found this to be the most efficient when it comes to reading code.  It's clear at a glance what's included where and in what control structure.  I've worked on some real crap in the past, some of which I had to reformat just to understand what the heck the person was trying to do - variable/no intents, nested structures with no way of differentiating where each ended, etc.  (In fact, I worked on one such program and the source of the problem is that the guy who wrote it got confused himself and ended a conditional too late - the compiler complained and he just added a closing structure to the end to get it to work, then shipped it off to the client's site.  Unfortunately, it was rarely used code, so it wasn't discovered until I was hired.  I got 'talked to' by my boss because the original programmer saw what I'd done and complained about my 'ruining' his program; I showed my boss the printout of his original code and my formatted version.  That was the end of my getting chewed out and he went right upstairs with the printouts and starting yelling at the other guy.  )

I've posted several scripts on this forum, so I won't post examples of my style in this thread, but here are some links to save you from searching (should you care to look at my coding style):

Keep a file updated with an online version
Detect brute-force password guessing attempts to a mail server
Spawn a new shell in the given port's directory and spit out dependency information as you do so.
Script to allow newsyslog to execute shell commands, albeit in an indirect manner
Perl script to codify wiping your rear end (unfinished & abandoned)


----------

