Note to editors of this page: please be sure _not_ to set the "ConvertSpacesToTabs" switch on save, or the examples are destroyed.
Is there any discussion etc about coding styles here?
Yep. Check out CodingStandard. In my opinion having, _a_ standard is more important than having _a particular_ standard --AlexVanDenBergh
'' What about CodingStyle or CodingStandard for languages that don't rely on curly brackets for scoping? I can see how this page applies, for example, to DelphiLanguage, but what is a good SqlCodingStyle? -- BevanArps
I prefer this
int f(int a, int b) { if(a<b) { printf("hello!"); return a+b; } return a-b; }instead of
int f(int a, int b) { if(a<b) { printf("hello!"); return a+b; } return a-b; }-- SavasAlparslan
Those are the two main styles, the difference being the top style is liked by programmers looking at the braces as the scope while the bottom style is preferred by programmers using indention as the scope. The indented scope is actually easier to read if you quit trying to find the braces and just look at the text indention. It also makes better use of vertical space allowing for more compact looking code.
There's a third mainstream style.
int f( int a , int b) { if ( a<b ) { printf("hello !); return a + b ; } return a-b ; }That's why in the current project we enshrined the standard that everybody can close braces wherever he or she damn pleases, with the only condition that the identation look should reflect the block structure.
Quite aside from how it looks, this has the problem that, when the last line of the block changes, the brace must be continually fiddled with, which takes more editing effort. Similarly the following less-than-universal comma style is helpful in initializers:
char *strings[] = { "one" ,"two" ,"three" };I hold that the editing effort should be the least of concerns in CodingStyle. First of all, code is much more read than edited, that's an universal observation that everybody seems to agree with. Second, I do expect people to do more thinking than typing when programming. The later is per good old EwDijkstra, but I know the principle became much less fashionable lately. In any case the extra editing effort necessary to maintain the third style is minimal.
I see your point of view, and that it could work for you, but I don't see that this would persuade people to switch.
That was my "insight" into the problem. The problem with enforcing (it is rarely persuasion ) strict CodingStyles on grown up programmers is that it is most like an invasion of privacy. So wouldn't it be nice if everyone would write in the style he/she is more confortable with ? Therefore pretty much all styles suggested on this page will be acceptable, even in the same codebase. Of course if someone is editing a file someone else's code he/she will have to adapt to the local style, however this should be a rare occurrence.
Yep. But also see DaveSmiths comments below about just using a PrettyPrinter. I don't mind at all making minor edits to a file that uses even pretty strange stylistic conventions, but when one is required to actually author all files in a strange project convention, the pretty-print-anyway-you-like-on-edit approach is nice.
Apparently the DaveSmith comment has been removed or his name trimmed - however, my current project is only one thing away from a wholly automated solution - the code is stored in the version control system in a minimal style, perhaps sans any indentation, and every checkout would prettyprint the module following the developer's personal style, and checkins would prettyprint into the minimal style. The only obstacle is that C++ has no good PrettyPrinter - the best I've found cannot keep one structure the same - it flip-flops between 2 indentions for some constructs -- PeteHardie
(Oops, I meant MikeSmith, not DaveSmith) Cool; pity you haven't found a good C++ PrettyPrinter; I thought maybe I just hadn't looked hard enough. If you find one, I see a plea on the PrettyPrinter page; good place to put a link. I'm sure someone could turn the GNU GnuCpp parser into a good PrettyPrinter, if it were worth the effort - which I suppose it hasn't been, so far. I've never seen even a perfect C PrettyPrinter, even though that's an easier job than C++. But I've often settled for whatever indent can manage. -- DougMerritt
I prefer the other one...
Opinions notwithstanding, this is the correct style:
int f(int a,int b){if(a<b){printf("hello!");return a+b;}return a-b;}Anything else is wrong.
Yikes! WhereDoTheBracesGo?! This particular style issue has been debated since the dawn of curly braces. I suggest you flip a coin to pick your team's style. If you're used to the one style it takes about ten minutes to learn to like the other just as much (assuming you try).
Or get a PrettyPrinter, like e.g. SourceStyler? (http://www.ochresoftware.com/ - commercial, Windows-only), and let people reformat each other's code to a style that suits them. -- MikeSmith
This is my favorite approach, since it's a win-win on an otherwise lose-lose religious war topic. -- DougMerritt
PrettyPrinters can mess up good formatting, so I wouldn't bother unless the code is really badly formatted. Don't get in the habit of running perfectly good code through a PrettyPrinter just because the brace placement isn't the one you like to use.
I used to use this form consistently:
int f(int a, int b) { if (a < b) { printf("hello!"); return a + b; } return a-b; }Now I use either of the two up top (with 4 or 8 character indent), it doesn't matter to me anymore. I can read both, no problem. The best argument both for and against lining up the braces is ease of copy and paste.
this is the style I'm drifting toward:
int function(int a, int b) { if (a < b) { printf("hello!"); return a + b; } return a - b; }The ugliest brace form I've seen (from the Lightspeed C compiler libraries):
int f(int a, int b) { if (a<b) { printf("hello!"); return a+b; } return a-b; }I have preferences about white space, but they're just preferences.
The Python C style guide has pretty good whitespace recommendations: http://www.python.org/peps/pep-0007.html
Here are some things that do matter:
/* don't do this */ if (a < b) callthis(); else callthat(); /* or this */ x = function1(); y = function2();Why is this a bad idea? It interferes with debugging - debuggers only like to set breakpoints on line numbers. You can't set a breakpoint on either of the if target clauses. This can be a real problem if the code is called a lot and your only interested in the one in 10000 case where one of the specific clauses is triggered. Setting a breakpoint in the assembly is possible, but it's tedious and a waste of time. Why bother? Just split up your if:
if (a < b) callthis(); else callthat();Actually, I prefer the one-liner because it looks better and doesn't waste vertical space. Scrolling sucks.
I always use braces - makes it MUCH easier to add lines - NissimHadar :
if (a<b) { callThis(); } else { callThat(); } if(a<b)callthis(); else callthat();and my debugger set's breakpoints just fine for those either on the if or on the callthis(), so maybe you need a better debugger.
A contrary rule of thumb for C++ classes:
My opinion has changed recently with respect to member ordering. I used to put public methods first (followed by private member vars), since the public interface is arguably more important to anyone browsing the code. However, I've recently been using the 'traditional' style of putting private members, etc., first, followed by methods, and it just seems faster to work with... although I can't explain why. -- MikeWeller
I was wondering if a person's preferred coding style said anything about that person. Can we make deductions about the person's personality like some people believe personality traits are revealed from a person's handwriting? -- PaulRuane
See InkBlotSoftwareEngineering
Most of the teams usually have their own preferred coding styles. If you just go around OpenSource projects, you'll find reasonable recommendations which frequently contradict each other. I've been using the CGI one for a long time though, http://www.sgi.com/grafica/ccode/
Buy TheElementsOfJavaStyle? ISBN 0521777682 (written by Scott Ambler and a bunch of then-RogueWave employees including AlVermeulen). Do what it says.
I'm not claiming that their coding style is really any better or worse than anyone else's, but at least it gives you a good starting point, and enables you to focus your efforts on the really important stuff: Like the customer's business needs.
For the code example we've been using on this page, I would probably write:
int f(int a, int b) { if (a >= b) return a - b; printf("hello!"); return a + b; }That is, I prefer to handle simple cases earlier in a function, and return from the middle of functions freely. But if not permitted to rewrite the logic like that, I'd prefer
int f(int a, int b) { if (a < b) { printf("hello!"); return a + b; } return a-b; }I also "cuddle" my elses, as in: /( )*\} else \{/ on a line by itself.
And no tabs!!
-- KarlKnechtel
how about this, it lets you visually ignore the braces, much easier to read since you only need to look at indentation. I do this mostly because I'm jealous of SmallTalk. I think I picked this style up from the guy who wrote BlocksInJava. -- RamonLeon
int f(int a, int b){ if(a<b){ printf("hello!"); return a+b;} return a-b;}tried it - didn't like it ;-)
See PersonalChoiceElevatedToMoralImperative
I think that one difficulty arises from the use of whitespace as 2 things - a code structure delimiter, and a readability aid. I sometimes see assignments lined up with all the ='s in a column, or all function arguments split out on separate lines, lined up with the first one vertically. Those are readability. Indents following if/then/else are code structure. Some things are both - alignment of subclauses in a large boolean condition, frex. I don't think that readability can have only tabs, while code structure seems possible with only tabs. -- PeteHardie
How about
int f(int a, int b){return a+b*((a<b)?printf("hello!"),1:-1);}Isn't it marvellous what you can do with ?: and ,?
Sure, if your point is to confuse the reader.
What about Lisp or Scheme, while we're at it? You can do just as weird things to those languages if you really want to, and there are a LOT more braces to mess with. Or if this page was only intended to discuss C-ish languages, delete this.
; Standard style (define (fact x) (if (< x 2) 1 (* x (fact (- x 1))))) ; Written-too-much-C style (define (fact x) (if (< x 2) 1 (* x (fact (- x 1))) ) ) ; Downright bizarre style (define (fact x) (if (< x 2) 1 (* x (fact (- x 1))) ) )I've only ever seen that second style in AutoLisp, and it seems to be the primary style. It's the default enforced by VisualLispIde.
There is a minor variant on the Standard style that says that the right paren that closes the first left paren on a line should be followed by a space, like this:
; Standard style - variant (define (fact x) (if (< x 2) 1 (* x (fact (- x 1))) ))The reason for this, is to easily determine where to break the line if you want to add another one.
Sure, here's pretty much all you need to know about good coding style for every procedural/imperative language:
Your tips are reasonable, but none are about CodingStyle. The first is more about levering language capability than applying CodingStyle, and it's largely governed by the language you're using -- for example, some languages reasonably and usefully support anonymous functions and/or classes. Your second tip is a good example of DontRepeatYourself and OnceAndOnlyOnce. It's more about good programming practice -- and common-sense avoidance of repetition and redundancy -- than CodingStyle. The last is also an issue of good (or not -- it's controversial) programming practice. However, how you format the comments would be about CodingStyle.