In Objective-C
can't you imply/omit the curly braces using indentation after the if(), Python stylee? I quite like that.
For decades, dour broadsheet the New York Times and its style guide have presided over the world of posh writing: its English usage manual serves as both a bible for upmarket writers and a blunt instrument with which to beat sensationalist tabloid hacks such as your humble correspondent. Now the Grey Lady has turned her hand …
Whereas in Perl, you have to put braces around the if-true part and the if-false part, regardless of whether they're just single statements or not. I quite like that since there's none of the fiddling around adding and removing braces (and potentially errors) when you change the number of statements in the if-true/if-false parts. Of course, it's also nice that perl gives you the 'statement if condition' and 'statement unless condition' syntax (without braces) too so that more than makes up for the enforced use of braces in the more traditional form.
Even in C, it's probably a good idea to use if (...) { ... } [else { ... }] even when you don't need to. Use it without braces and occasionally you'll come across a macro that expands to several statements, probably leading to very puzzling and hard-to-debug program behaviour... And as I mentioned, adding/removing parenthesis based on the number of statements is tedious and error-prone. Your essential logic hasn't changed (just the number of statements), so why should the syntax need updating?
IOW, thumbs up for mandatory/orthogonal use of braces!
Always using braces does improve the quality of the code as such. However I have experienced enough bad merges in tools in git and hg that were caught by the braces merging in a way that gave a compiling error that I now believe it is always best to use braces.
(I don’t care how many space, or if the first brace goes on a new line provided the code is consistent.)
I completely agree, if for no other reason than it saves me 3 keystrokes (and saves 3 bytes of storage, of course...)
And why does an if need a block after it? for a single statement it is a complete waste, and looks messy!
Merkins have butchered the English language, now they are trying to do the same to C-style languages too!
"And why does an if need a block after it?"
Defensive programming. It stops you making an idiotic mistake later when adding a 2nd statement to the if. We've all made that mistake... not that I'm claiming I always do the bracing, it has however saved me a lot of debugging time since I got into the habit.
// oops 1
········if (a)
················if (b) BOFH();
········else not_a();
// oops 2
········if (a) if (b) BOFH();
········else not_a();
// safe
········if (a) {
················if (b) {
························BOFH();
················}
········} else {
················not_a();
········}
I have never understood why people would want to use spaces. I know it can look a bit wide if you haven't set your editor up right, but it never looks wrong. You never have to reformat vast swaths of code which have unaccountably ended up having three spaces instead of four, which I regularly get in 4-spaces code. You hit the tab key, and you find it doesn't line up. Then you have two options, hit space again to line it up, or hunt down the incorrect line and correct everything that was entered after it, by hand. There are no automated tools to help do that.
And anyway, once code is tab-indented, every engineer can set tabs to their favourite number of spaces. The only problems that might arise are non-optimally laid-out comments.
TAB -- works every time
Spaces -- fails every time
"correct everything that was entered after it, by hand. There are no automated tools to help do that."
Seriously? Are you still using a VIC 20?
I don't care if you use spaces or tabs, as long as everyone who touches the code does it the same way. Even better, have a hook in your SCM to fix indentation to whatever the company policy is.
" There are no automated tools to help do that."
Have you no editor? Have you no formatting utilities? Good God, man, the C beautifier isn't that difficult to use! What are you using, ed or notepad?
As for coding standards, they change from company to company, and usually are close to whatever the auto-formatting the IDE gives you. VS C# is different from Eclipse Java, blah blah blah. Whoopee. I've worked in places where it was tabs, and places where it was spaces. Put your { here or there, yadda yadda yadda.
The main thing is consistency. Be consistent, and stay consistent.
The main thing is consistency. Be consistent, and stay consistent.
Our toolset won't even accept code for putback into the SCS repository if it fails the style rules. Some of which I hate, but consistency is rightly enforced.
Every so often I have to go write a private bit of code, just for me, so I know I can still do it right
You use spaces if you have multiple people editing the same files from in mixed environments, like having some people using various Windows- or X-based editors, some in terminal vi or emacs, etc. Tabs have arbitrary visual width, and you can tell people to set whatever they use to display a certain tab width, but you cannot always enforce that they all do it. So then you get people mixing spaces and tabs (often unintentionally) in ways that look like the code is aligned in one editor but not in someone else's.
Spaces avoid this ambiguity. No editor displays five spaces as anything other than five character positions, unless, God help everyone involved, someone is editing code in a proportional font.
Hehe probably my most unpopular post ever, and I don't care.
Tabs to indent, spaces to align to text. It always works perfectly, however tabs are set.
OK, there may be tools; a pretty-print would work OK, so long as it was configured for your style, and your style was very fixed. But spaces to tabs doesn't work when the number of spaces is wrong, and in my experience that happens a lot. YMMV.
Our company has decided to use the IAR compiler to build the code for our embedded system. The reason was that it generated the tightest ARM code and the project we had contained 251K of executable code in 256K flash memory. The IAR compiler was the only one that could fit the code into the allotted space. That being said, IAR is the horse that we hitched our cart to, and we aren't switching to a different one.
Last month we encountered a bug in the IDE portion that caused builds to fail. I traced it down to a combination of factors, one of which was a certain configuration of tabs in the source file. I eliminated the tabs and the build proceeded normally.
I have no idea why the IDE would be concerned with tabs in a source file (although I know that there is some scanning of the files to determine dependencies, etc.). I've been very lenient about tabs in our department (even though we have a coding standard that forbids them) but they started affecting our work so I had to remove all tabs from the project and tell all the software engineers that tabs were no longer allowed. Fortunately, all the engineers agreed this was the best way to go.
By the way, we used to have an engineer that swore upon tabs and got angry when my editor automatically converted all tabs to spaces when I edited the file. One day he was entering some aligned character strings into the code, and he used tabs to perform the alignment. The C compiler didn't care and dutifully added the tabs to the code. The display driver only worked with the standard space-to-tilde characters and generated a wild pointer when it came upon the tab which wasn't in the character table. The system crashed miserably and some serious debugging time was wasted trying to find the bug.
The moral of these stories is to stick with stuff that's guaranteed. The space is guaranteed to give you one character width regardless of where it's placed, and is guaranteed to work with virtually all display drivers. The tab will not give you a guaranteed width, and may cause strange behaviour or even cause a crash if used.
I can appreciate the logic behind tabs being superior to spaces, but the reason why spaces tend to be preferred by collaborative projects and standards is:
- It is guaranteed to look the same in every editor, without needing to change settings.
- When someone using a certain tab size adds spaces to get to a particular column, or when someone uses tabs on some lines and spaces on another, it can look absolutely terrible when someone else opens that file.
- Even if you've got your editor set up nicely, what about when you open the code in a terminal using something like vim?
Just set your editor to change all tabs to spaces. It's the safest for consistency, and it means the file will always look the same for everyone, and you can still use the tab key for it.
Using tabs is basically forcing other people to adopt your style: they have to change their editor to your tab width just to view your file, and change it again when opening someone else's file. Whereas if you use spaces, you are catering to everyone: even if they use tabs, it'll still look how you intended for them, because spaces are always the same width.
Use tabs, or spaces. Not both.
It's not the editor that has the problem, but the diff tool you use prior to submitting your code to your <repository of choice>. If the diff tool has a different setting for tab width, then you see issues with the indenting of the code your reviewing.
The fixes:
1: set editor and diff tools to use the same values for tab width.
2: use <number of your choice> spaces instead of tabs.
I use 4 spaces instead of tabs, and I set my tab width to 4 spaces in all my tools. This leaves me free to express my opinions on where the {} go, and whether I should indent 'case' markers inside my switch statements.
use tabs!
A practice that keeps all of you code off the r/h side of the screen leaving you with a lot of wasted real-estate on the left.
That's one the the things wrong with tabs.
Another is that you can set what they mean - which means I can set them to be something different to you. I once spent some time trying to figure out why Zork output looked different by one "space" on my terminal (yes - a green-phosphor terminal) to others. Until I discovered it was using tabs in its output, and I had my tab stop set differently. On that day I removed them all, and have never liked them seen (I'd never seen them used before).
I'm also sure that I once read Leslie Lamport (of LateX) refer to tabs as the "Spawn of the Devil". I can find no reference to this, though. But I agree.
I normally prefer tabs too. However as others have pointed out, different editors have differing opinions as to what is meant by a "tab" key.
Some will insert 4 spaces, blindly.
Some will insert a tab character.
Some will insert spaces to line up with the next tab stop.
Some will insert mixtures of spaces and tabs.
I use (g)vim personally. :set list is a godsend! Tells me exactly when I've accidentally put a tab or space in the wrong place. Plus, vi modelines mean it can deduce what settings to use automatically.
One IDE I'm using at the moment though, NetBeans, I find really annoys me with respect to whitespace handling. Sure its automatic templating of files, code re-factoring and automatic checking and completion is nice, but it frequently leaves spaces at the end of a line (a pet hate of mine) and I constantly battle with it over what I meant by 'tab' and 'enter' keys.
I normally steer clear of IDEs and IDE-embedded text editors in particular, but in this project, I'm not writing the software purely for myself, but so that others (many of whom are new to programming) can pitch in and help, thus I aim to set things up to make it easier for them. Once I get things established, I'll probably switch back to using gvim for the actual editing, and just use NetBeans for the refactoring/project management side of things.
Guess having been an emacs user many years ago, but then forced to learn vim when I crammed SuSE Linux 5.3 on my 386's tiny HDD and found I didn't have room for anything else, I've grown used to it and now find everything else alien by comparison.
FIGHT FIGHT FIGHT
Pretty much most people these days are taught 1TBS, but I still do Allman, and I maintain a bunch of code in Whitesmiths, and I do a bit of BSD kernel hacking, which obviously has to be in BSD KNF.
The NYT scheme looks a lot like 1TBS with added extra rules.
I work with guys who do that in Delphi blocks...
If condition then begin
..Stuff;
..Stuff;
end;
Really annoys me.
if condition then
begin
..stuff;
..stuff;
end;
Is far nicer. Sure they save a line, but they complain if I use
if condition then single_stuff;
So they can't claim space saving!
Is there any kind of Markdown or formatting we can use in these comments, code just gets split into paragraphs!
"Is there any kind of Markdown or formatting we can use in these comments, code just gets split into paragraphs!"
Post a link to a picture (as in .PNG) of the code in question?
It would be entirely in line with El Reg's editorial policy of using pictures where tables are what is needed. IE it would be stupid due to being avoidable given a bit of common sense.
"Well, they're wrong. Braces come in pairs and should be visually paired up by putting them in matching columns. Putting the first one at the end of the line is just stupid."
Having the brace pairs match up doesn't really matter, though - having the closing brace line up with the relevant function/method/class/other language construct is what actually counts. As such your extra newline just makes for more whitespace - probably you are the sorts of programmers who judge your success by line count, the higher the better? ;)
On the other hand I'm a former paid JAPH, and as such spent years working with code which looked like an explosion in a punctuation factory - and loved it - so my opinion on this matter can safely be ignored.
This post has been deleted by its author
But if you forget to put in the opening of closing brace, you can end up with a totally ridiculous block structure and not notice. Lining up braces means you can check them by eye.
Of course you're never going to notice - after all a compiler for a C-like language is not going to fail mid-way through one is can't make sense of those mismatched braces.
The reason for a brace at end of lien is a simple one - it saves space, either on screen or on the page. I've lost count of the times where a C listing has shrunk by several pages when K&R style is adopted. That isn't just about saving paper, it means you can see more of your code at once. For people who actually read and review their code that's a very definite plus.
But then again, it seems most open-source projects these days are to all intents and purposes write-only. Emacs in particular has a seemingly infinite number of instances where a new variable is declared that exactly duplicates what is being done by another declared a few lines above.
"Spent years [writing (my correction] code which looked like an explosionin a punctuation factory".
|
|
|-> You are right, your opinion can be safely ignored.
The indentation of a program is a visual representation of the set relationships of the code being written. If you break the rules, you can't do things like finding errors by scanning down a program and finding the misplaced bracket.
Much of the coding style "controversy" gets a "Meh" from me, but the logic of aligning the opening and closing braces (for those crazy languages that use them) makes sense to me, whereas I never grokked why you might want the opening brace on the same line as the statement it belongs to. I never really got why there's so much fuss about tabs/spaces either (though personally, tabs seem to be better, as individual coders can have their own preferred indenting "width" [set by the IDE] without disturbing another coders preferences *and* they're more storage-efficient than multiple spaces).
Anyway, have an upvote.
Bellyfeel doesn't seem appropriate - grok is "to drink" - a sentiment appreciated after much hunting through source code - mailing lists and man pages to finally make a leap of intuition having drunk deeply of the well of information.
Bellyfeel is more like uncritically accepting "goto is evil" without wondering why.
> It's not wrong at all. Just depends on your preference, as long as it's all consistent.
Exactly. If you cannot read and maintain any consistent style then you need to think of a different career. There are far harder things in programming (understanding what the customer wants for a start).
OTOH one can have a preference: one true brace style is called "true" for a reason :-).
A coding style only needs four unbreakable rules:
1. Be consistent.
2. Indent to make program structure clear.
3. Name's clarity (eg. long and more more descriptive) should reflect their scope.
4. Tabs/spaces [choose one for the team/organisation, delete the other] only.
/Everything/ else is subject to argument and exceptions.
Yes, definitely. Braces should follow the indent and ideally have a line each for visibility, not have one of them stuck at the end of a line of text somewhere.
Of course, that still leave the argument as to whether they should be aligned under the 'i' in 'if' or whether they should be indented with the code :->
(I'd put them under the 'if' but don't let that get in the way of any flame war on the subject.)
Ultimately remember that the code is supposed to be easy to read and maintain. Be nice to those who come after you and have to fix all those obscure bugs you've lovingly hidden in the code. If someone's used the wrong style then stick to their style when modifying their code, it keeps it more readable than the case where the bracket position depends on who wrote that block of code.
Quotes, double quotes, parenthesis, and and brackets also come in pairs do they get their own line and matching columns?
Braces are irrelevant.
Correctly indented code can be read with all braces removed. I don't need to see them at all never mind dedicate a whole line to each.
Wow. Big up/down-vote ratio for that. I hold the opposite view, that "if (...) {\n" is better. For two reasons...
1. Vertical space is precious when editing, especially given most people (OK, I generalise) are using 1920x1080 monitors. Putting the brace on a separate line means one less line of code visible on screen without scrolling for each if/do/while/whatever. That means more scrolling and more getting lost, especially if your only way of matching braces is to keep track of how far you think the matching one should be from the left of the screen. Simply put, better use of vertical space = improved readablity.
2. It's no harder to trace back up the screen vertically to a statement than a brace. You could even use tabs and have your editor display them visually so that it's easier no matter which style you decide on.
Oh, and
3. Your editor probably has something like emacs's blink-paren command (or mode) to show you where the matching brace is anyway so it probably makes any religious argument one way or the other moot.
I don't know how many times I've done this:
if (Test == 1)
---Line1 = 1;
---Line2 = 2;
} else {
---Line3 = 3;
---Line4 = 4;
}
I've told all the people that work under me to put braces on their own line aligned with the if. We work in the medical industry and we can't afford to have bugs in our code that could jeopardize lives. I wrote a coding standards document for our company based on Netrino's standard that helps us write bug free code. It's anal but it gets the job done.
If vertical space is a problem, then either your coding style is wrong or you need a better editor. Nobody should be writing functions containing hundreds or thousands of lines of code. If I have a function that's over 100 lines, I'll look for ways of breaking it up into multiple functions that are more readable and maintainable.
As for the editor, I use SlickEdit. The document window can either be in the main SlickEdit window or in it's own child window that can be moved anywhere on the screen. I use the Terminal 6 font which gives me over 120 lines of code in the window. And my 1680x1050 monitor can hold three files side by side. Yes, my editor can search for matching braces, but I've got better things to do with my time than trying to find mismatched braces. I actually haven't used that function in over a year because our brace standard makes it so easy to see any mismatches.
By the way, for anyone who doesn't see the problem in the snippet above, the first brace is missing. Aligning the end brace with an if isn't enough to ensure that the code is correct.
I think I'll wait until the Chicago Manual of Style weighs in.
Jokes aside, style guides can prevent a certain amount of irrational anger in a group coding effort. I have my preferred style, but setting up one's editor for the employer-of-the-month's style can save a lot of aggravation.
(Oh, and of course indentation should be done with tabs. This fad for indenting with spaces is troubling.)
"What goes into the file, however, should be plain old spaces -- however many you've agreed on with your editor."
So what happens when someone edits my code who wants 2 spaces instead of 4? Or 8? Or 5?
If they are left as tabs they can be adjusted by an individual's preference in their editor.
It's been a while since I last wrote any C but, putting the bracket on the same line, or the equivalent in whatever language you are using, just does nothing for clarity, unless it's a one-liner where it is obvious what's going on. I've never understood why people have to cram their code into the smallest space possible, it's not like the extra whitespace is going to make a jot of a difference to the complied code and gone are the days when you have to try and cram your source code onto a 256K floppy or worse! Coding shorthand so often just obscures the flow, especially if it's the first time you've looked at it for months or years or you have the misfortune to inherit someone else's undocumented project!
I agree with you about where the { should be.
However, it is my understanding that the reason for having it on the same line as the if() is that in the days of manual teletypes it saved waiting for the carriage return AND saved paper - remember that once upon a time we didn't edit code on a screen.
It also saved a card if you were submitting your code that way.
Gah, no, putting the open brace on the same line as the controlling block is simply K&R style, and has a long history. There's two reasons, 1) So it's immediately clear what is controlling the block of code, and 2) as defensive coding style against accidentally forgetting to put in the brace.
I personally have no problem with either style, so long as it is entirely consistent in your corpus of code. Mix it in one program and you DIE.
That said - checking your code by visually looking at indents is only going to work when you haven't screwed it up. Check your indents by using an editor which properly shows the scope in a gutter (most good IDE editors), or a least will pop you back and forth from the start to the finish (good old vi). Nice indenting is for ease of reading, NOT debugging!
Why write a text guide for humans to read, why not write a python script that will format the source to their standard?
I had to do this for my A-level computer science project... My tutor complained my code didn't have enough white-space. To my mind it had the perfect amount of white-space, just enough for the BBC Micro interpreter to identify token keywords from variable names.
So I wrote a program which took my code and converted it to code with more spaces.
Tutor was impressed, and asked why I hadn't written it like that before... So I loaded up the new space filled program and typed "RUN"...
"Out of memory" came the reply... :-D
#! /bin/bash -e
sed <"$2" \
's!\([ \t]*__attribute__((.*))[ \t]*\)!/*OTBS<\1> */!;'\
| indent -st -npro \
-pmt -bad -bap -bbo -bc -br -brf -brs -bfda -bfde -c33 -cd33 -ncdb\
-cdw -ce -ci4 -cli0 -cp4 -ncs -nfc1 -nfca -d0 -di0 -hnl -i8 -ip0\
-l78 -lc78 -lp -lps -npcs -ppi2 -nprs -psl -nsaf -sai -nsaw -nsc\
-nsob -ss -ut\
| sed 's![ \t]*/\*OTBS<\([ \t]*__attribute__((.*))[ \t]*\)>.*\*/[ \t]*!\1!' \
| sed '
s/^) {/)\t{/
s/} else {/} else\t{/
/^[ \t]*if .*[^{ \t][ \t]*$/{N;s/[ \t]*\n[ \t]*/ /}
/^[a-zA-Z0-9_]\+($/{s/^\(.\{1,6\}(\)/\1\t/;N;s!\n[ \t]*//!\t\t\t//!}
' >"$1"
This post has been deleted by its author
even if it's only a single line, I'd prefer to seperate my if statements
if ( !error )
{
return success;
}
likewise I like method headers, function headers, comments that explain why we're doing rather than what we're doing. In the above a comment along the lines of "returns a success message if there is not an error" makes me want to bash my head into a wall. If you need a comment for that then you probably need to be warned that the coffee is hot and might burn your tongue, or that not everyone likes spouts.
I set my tabs to 4 spaces in VS, but that's just because it seemed like the nicest fit.
Additionally I prefer putting in spaces around braces and parenthesis quite simply because it makes larger functions easier to read, and easier to track the last closing brace.
Meaningful method names are a must. Likewise for params. I don't want to see a a1 a2 a3, I'd rather see *player player1 player2 player3.
Prefer camelCase to snake_case, it's somewhat grown on me. Anyone who mixes the two ala this_FunctionalMethod should be shot in the foot.
I think that about covers the basics. *begins writing his own style guide*
I suppose by the end of it the only style guide that really applies is what's already in place.
As much as I prefer
{
stuff
}
fed may prefer
{
stuff }
and harry may like
{ stuff }
Each is just as viable as the last (code isn't set in stone like grammar) so really the style you use should be the style of the rest of the code.
If an entire project is done this_is_my() { face }
then I'll write it in that way. If it's my own project, I'll write it the way I prefer. It's really down to the project, it's kind've why coding standards existi in companies (and if they don't then they should.)
2 spaces per level for me. Tabs mean any significantly nested code just disappears off the RHS of my screen or, worse, gets wrapped by the editor. I put the opening curly on the same line as the 'if' and the closing curly in the column below the 'i'. 1-statement blocks don't need curlys. Statements in the block are indented. Works for me, but feel free to flame or downvote.
In VI you can easily remap the number of spaces per tab, I would imagine most new-fangled editors have the same option somwhere.
Which is precisely why you should use tabs instead of spaces, actually. Because then someone else who dislikes reading compacted two-space-indent code can view it the way they want when they open it in their own editor.
Except when you end up having to read code that someone's peppered with tabs on someone else's machine where they haven't bothered to set up a proper editor or they really like 8 characters per tab and anything over a few levels of hierarchy means that the code's disappeared off the edge of the screen, nothing lines up and it's impossible to follow. Fixed spacing using spaces works universally, unless you're a freak who uses variable-pitch fonts....
"Whereas the Reg programming style guide requires that method and variable names contain alliteration and dodgy puns."
Wot, like using a pointerSisters struct for a double linked list? superCalibGoesBallisticCallbacksAreAtrocious() when dealing with a calibration fault? Given our headlines are written to make you think (or blurt out loud) "My god! What?!" and click on the link at once out of raging curiosity, I'd say our programming style would be "rhyming esoteric" that'd make you reach for the comments or VCS for help.
Of course, our backend systems are so very cleanly written (in perl).
C.
Use a decent editor, of course, and when you close the brace it matches it visually with the corresponding open. If the opening brace is off the page Emacs will show the matching line in the message-line. If you put the opening brace on a line of its own THAT COMPLETELY F*CKS IT!
I've always been hoping someone would write a code-styler that we could hook-into revision control so the in-repo copy has no spacing at all (thereby saving all those "extra bytes") but when you take your copy it re-formats the files to your favourite format.
New York Times eh ? I think I'll wait for Hello! to pitch-in...
glad to see the Allman style supporters are out already.
Figured I'd chime in on the one liner if-- this guideline from NYT is clearly from someone who's never written industrial scale code (grabs flame-proof suit). In a good code base, pretty much every function returns error. If you have a function that acts as a switch between hundreds of of different functions all not quite alike, you get a crap-ton of tedious code like
if(function != Success)
{
goto cleanup;
}
well, of course, that is too dang long when you have hundreds of the little buggers all over the place, but the simple, legible
if(function != Success) goto cleanup;
is of course forbidden by your coding standards, so you get the wonderful error handling macro to wrap things up in to bring them down to one line within the remit of the coding convention. Like so:
CHECK_ERROR(function);
Now, this doesn't look too bad, until you actually try to read code that has this stuff in it. I'm not sure about all of you, but when I scan that line, I see CHECK_ERROR, not function. Yes, there are other advantages to this sort of macro, but the one-liner if is miles ahead in terms of legibility.
MACROS??? They are the devil's work.
I know of only a couple of (arguably) legitimate uses of macros - defining constants, and defining log and assert macros that you may wish to redefine and compile-out for production builds. Anything else is an abhorrence.
As for the curly bracket debate, I agree with what most people are saying. having the opening brace on the same line as the 'if' just makes reading the code more difficult than it needs to be. I hate it. Oh, and ALL conditionals should be followed by a block ({...}), even if they are just one-liners.
As for "goto" - You're kidding, yes?
...and while we're at it, all functions have precisely one entry point. They should have only one exit point (at the end).
if (...) return;
....is awful. It breaks the flow of the code, it's ugly, it's just not bloody-well British!!!
A function with more than one exit point is broken and indicates faulty analysis. It needs to be rewritten or possibly reexpressed as several functions. We all, of course, analyze problems fully before starting to code, right?
As for a "function" with several entry points, how far can that be from spaghetti code?
Multiple entry points is really just a glorified "goto" mess but with the option of some locally visible variables. Quite why one would care about variable visibility if using such an horrible approach is left to the readers...
However, I think you are over-reacting with the multiple exit point issue. For example, if is not uncommon to have something like:
int myfunction(char *ptr)
{
if(ptr == NULL) return -1;
....<some code...>
return 0;
}
While you could code this as
int myfunction(char *ptr)
{
int rc =-1;
if(ptr != NULL)
....{
....<some code...>
....rc = 0;
....}
return rc;
}
I doubt it is any easier or more understandable to the reader. And that is what code is about, not just doing the algorithm, but making the process as transparent to the reader as possible.
p.s. A good read are any of the Numerical Recipes books (3rd edition is only C++), and not just for those with hard maths problems to consider.
Macros are useful for building tables of names stuff, sort of:
#define ADD_VAR(x) {#x, (char *)&ptr->x},
table_t something[] = {
ADD_VAR(wibble)
ADD_VAR(wobble)
};
Which creates an array like:
{"wibble", (char *)&ptr->wibble},
{"wobble", (char *)&ptr->wobble},
etc.
As for "all functions have precisely one entry point" you have obviously never used old FORTRAN where a subroutine could have multiple entry points as well as exit points. Now that really is the Devil's work!
My favourite idiom for "pre-flight checklist" code is to use a one-shot do/while loop, as follows:
bool passed=false;
do {
if (function() != Success)
{
log("function() fail");
break;
}
// line up ducks for function2()...
// ...
if (function2() != Success)
{
log("function2 fail");
break;
}
// etc, etc.
// finally, indicate success
passed=true;
} while (false);
This has the major advantage that any heap objects instantiated inside the do {} are properly disposed of (something goto can't guarantee), and if you use C++ and "Instantiate-to-acquire", you get your failure cleanup for free too. The major disadvantage is that the intent is not immediately obvious from the code -- hence my describing it as an idiom.
This post has been deleted by its author
Having gone through style discussions and committees far too often, I know better than to try to say much that is specific. But,
1) do not use the capabilities of your editor to change the meaning of a TAB. A TAB goes to an 8 character position. Never change that. If you do, you will be looking at some awful messes in the future if you start working with people who do things a bit differently. If you want, say, 4 character indents, then just tell your editor that. It's easy in things like the various emacs's and in vi/vim. Do not use a text editor that cannot do it.
2) as others have said, if there is a house style, use it. You will save yourself and your co-workers a lot of pain.
3) you should only have to type a single key (if any!) to move to the correct column for the next line of code. If you find yourself having to manually space and/or TAB over to the proper column, then get yourself a proper programming editor. The abovementioned emacses and vi/vim are free for all platforms.
4) @ Hungry Sean: never, ever hide control constructs in macros. Never. Use macros almost entirely for constants (including properly parenthesized constant expressions). Beyond that, and you are asking for trouble. See below.
In general, things that you might decide to do as a self-taught one-person programmer will often not work out at all in a programming team. So, on your first move to a team, be prepared to accept changes. If you don't, you should be fired.
Surely the one single requirement for style of coding is:
that you can read and understand it, that your colleagues can do too, and when you've gone to another job the person who replaced you can read and understand it.
(with proviso that a certain skill level may be required - Jane & John books bs Milton etc)
The space was designed in the earliest written languages to delineate between words.
The TAB was designed in the earliest typewriters to provide a means of aligning things so that their position has an implied relationship with other things in that same position - such as a tide-table or bus time-table.
Use the right tool for the job: a TAB for alignment and NOT a space.
I wonder if the NYT have anything to say on the excruciatingly annoying habit of TV & radio presenters to say "forward slash" when they actually mean "slash". There is no defense of avoiding confusion as they're only ever reading out things which CANNOT have a back-slash (Web addresses, e-mail addresses, SMS text messages, or plain old English language).
The only people reading out something where they might include a back-slash and therefore might (still incorrectly) want to be clear when specifying a slash, are scammers from India pretending to be from Microsoft support.
This post has been deleted by its author
They do not write dates backwards: 2013-08-04 is as sensible as 4/8/2013. No, they use the order month day year, which is not only unreasonable but means that 9/11 means something different according to convention, whereas 2013-08-04 is unambiguous.
I believe it was John Quincy Adams who did it that way, and it is now embedded in the Constitution.
Only the Japanese have the "correct" date format with MSB-left as in 2013-08-06
Those in the USA have sadly converted the spoken way of "August the 6th" in to numbers, hence the dumb approach.
Tip: Always use letters for the month, as anyone reading your text will understand that Aug is the month no matter where in the order it is placed.
Spaces accepted by every compiler.
TABs might glitch some software. I know "TABs are white space yadda yadda" (except of course in whitespace).
That said I presume all modern editors can accept tab keypresses and output them as spaces but when the re-read the file use tabs for the on screen version.
Someone mentioned even vi can do this so I guess that should be any modern editor beyond notepad.
Here's the thing. If 1 person writes the code they can use whatever style they want and if they don't use it consistently then it's their problem to figure out. So as long as they are a)The only developer on the project and b)Stay with the project from first code to retirement no problem.
Now how many of you have actually experienced that little fantasy IRL?
Not many I suspect. For the rest of us I'd suggest the problem is not what style to use it's using it consistently. Us meatsacks have real problems sticking to x spaces on each and every line of several thousand lines of code.
So I guess this will join the other style guides on the shelves (Kernigham & Plauger anyone?).
Pick a style for your project and STICK WITH IT.
You can make more sense if everyone agrees on what you are doing.
From my telephone wiring days: Neat wiring doesn't fail. The implication being if it failed, it wasn't neat. The same goes for programming. Make it neat and readable, most will follow from that. "Clever" code requires more time to understand, and is prone to errors. Just don't do it.
As for spaces vs. tabs: Sometimes the code is displayed in a proportional font. Spaces aren't too compatible as they differ from letters that you want to line up. Tabs are usually better. Of course, programmers shouldn't use a proportional font, but some times it gets in the way. Email comes to mind as a particular mangling environment.
As always: Your mileage may vary, see store for details.
Python is awesome for some things, but it depends hugely on your problem space.
An excellent example of what can be done in Python, is XBMC.
A lousy example of what can be done in Python can be found here:
http://comments.gmane.org/gmane.comp.python.org.uk/2749
The Quartz platform is written in Python and is dog slow (application start times can be measured in ice ages) and as for robustness? Hah, please don't make me laugh.
Every time a team pushes a change to Production, there's a real chance that their revision of a particular module/component will break something else which isn't really something you want to happen in a Prod environment. That's what they mean when they say Agile, it means stuff gets broken, frequently.
The { in the early C compiler was a statement for "begin a new stack context" except after the "if".
That use can be demonstrated with main() { { int i; i=5; { int i; i=3; }; printf("%d",i); } } and which results in a 5. This detail was very important when using setjmp and longjmp.
I prefer braces to appear on the line after the condition and I prefer tabs to spaces, but that's me.
What annoys me far more than any spaces/tabs and brace position argument is when programmers are too lazy to include decent comments about what their code is doing. I've seen functions of over 150 lines with zero meaningful comments. It's stupid, it's unprofessional and it wastes the time of anyone who has to pick his or her way through the code to figure out what it's doing.
And if you've got decent comments there's no need for really long variable names that look like they should be the names of Welsh towns.
Comments can get out of date. You can also end up explaining the function twice: once to the compiler and then again in English in the comment. Well written 'self documenting code' alleviates those problems, particularly if you include assertions. But, as always, it's balance. If a function is doing anything non-obvious it should be explained. And I have to eat my own dog food: and sometimes I do come back months later and find I can't understand it and have to add clarification or better naming; so we learn the art.
But I agree, camel case is hard to read once you have more than one capital in it. C-style underscores are quicker to absorb. But ultimately you have to follow the platform API.
I don't get all these coding style wars. The computer is well capable of formatting code to any style we want, at the touch of a button, oddly enough. Its what we programmers do; write programs to do stuff like format code.
So have a script automatically format code to the house style when it is checked it in. And if you use an IDE, configure it to format the code you are reading/writing to however the hell you like it, when you check it out. What's the big deal?
...in a defunct multi-national far, far away I remember these rules
All procedure names had to beging with the letter 'z'. All modules had to be given an eight digit name which was given to you by the great database on the mainframe and comprised of four random letters, two letters for the market targer and two for the version number which made for near impossible coding.
The program name had to be composed of the same naming convention and it wasn't long before someone was asking "Who is working on JSYGAX02 ?"
Oh and nothing more than 73 characters wide of text on a line otherwise the compiler would choke.
The company deservedly went to the wall. I wonder if any other readers recognise this clueless outfit.
Tabs vs Spaces? 4 Spaces. Tabs create trouble. People go *from* Tabs *to* Spaces. Who moves the other way?
Discussions of Tabs versus spaces look like this:
Spaces: you can get more code on the screen. Tabs:You should not need to; refactor if you do.
Spaces: you can work with any editor. Tabs:You should not have to. Everyone should get, learn and use another editor.
Spaces:the world is not perfect so spaces and tabs get mixed and its a mess: Tabs:That should not happen.
Spaces:but it does. Tabs:but it shouldn't.
Spaces:good luck with that. Tabs:gtg, mixup with spaces and tabs check-in. Idiots.
Spaces:been there. Thankfully learned my lesson.
Eventually, as you move from environment to environment you will find that using Spaces just means less trouble.