back to article Can't agree on a coding style? Maybe the NEW YORK TIMES can help

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 …

COMMENTS

This topic is closed for new posts.
    1. AbelSoul
      Headmaster

      "(I mean, honestly, braces on the SAME line as the if()?)"

      Indeed.

      I prefer the:

      if (el_Reg)

      {

      NSLog(@"Another top headline");

      }

      style.

  1. John Gamble

    Or, Alternatively, the UPI Style Manual

    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.)

    1. Munchausen's proxy
      Pint

      Re: Or, Alternatively, the UPI Style Manual

      Personally, I'd say that indentation should absolutely be done by pressing the tab key. What goes into the file, however, should be plain old spaces -- however many you've agreed on with your editor.

      1. John Gamble

        Re: Or, Alternatively, the UPI Style Manual

        Which is completely reasonable.

        (I find it interesting that we're getting downvotes over indentation style. Obviously the obsessive-compulsive indenters are out in force today.)

      2. Dr. Mouse

        Re: Or, Alternatively, the UPI Style Manual

        "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.

  2. Anonymous Coward
    Mushroom

    Tabs?

    As icon

    1. Steve Foster
      Devil

      @j arthur rank

      Hmmm, your troll bait doesn't seem to be working today, for some strange reason (or perhaps the moderators are simply deleting them).

  3. hopkinse

    curly bracket hell....

    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!

    1. Len Goddard

      Re: curly bracket hell....

      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.

      1. John Gamble

        Re: curly bracket hell....

        Huh. Was there a time when punch cards and curly braces ever intersected?

        (The only time I ever used punch cards was for the CDC 6000 series of machines, and braces were not in its character set.)

      2. Pet Peeve
        Boffin

        Re: curly bracket hell....

        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!

      3. Gordon 11

        Re: curly bracket hell....

        remember that once upon a time we didn't edit code on a screen.

        Remember that once upon a time we didn't write code on teletypes - we used proper punch cards.

        But in those days braces were for holding up trousers, not for programming.

  4. Martin Kirk

    I always position the leading { on the line following the conditional. This way it is at the same indentation as the closing }, and it is much easier to spot errors.

  5. Steve Evans

    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

    1. Robert Forsyth

      re: PrettyPrint

      Me too, first year of Computer Science, but I see this

      http://en.wikipedia.org/wiki/Prettyprint#Example_of_formatting_and_beautifying_code

    2. Flocke Kroes Silver badge

      gnu indent is your friend

      #! /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"

      1. Werner McGoole

        Re: gnu indent is your friend

        Nah. Displaying a logical document structure in a variety of interesting ways is what CSS is for. I'm sure it'd work.

        Keep it simple.

        Ahem.

  6. Spiracle
    Coat

    Grey?

    It's 'the Gray Lady' that side of the pond isn't it?

    1. Anonymous Coward
      Anonymous Coward

      Re: Grey?

      "It's 'the Gray Lady' that side of the pond isn't it?"

      Not always. Bostonians tend to spell proper like wot we do.

  7. This post has been deleted by its author

  8. wowfood

    Personally

    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*

    1. lurker

      Re: Personally

      Dear god, your poor mouse wheel!

    2. Anonymous Coward
      Anonymous Coward

      Re: Personally

      "even if it's only a single line, I'd prefer to seperate my if statements

      if ( !error )

      {

      return success;

      }"

      Well personally, I prefer:

      if ( !error )

      {

      return success; }

      Makes it a bit easier to find the one you've forgotten to put in 8-).

      1. wowfood

        Re: Personally

        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.)

    3. Dr. Mouse

      Re: Personally

      "*begins writing his own style guide*"

      http://xkcd.com/927/

    4. Tim99 Silver badge
      Headmaster

      Re: Personally

      There's a rat in separate...

      I used this icon - No spelling Nazi icon >>>>=============>>

  9. John Sager

    Indentation

    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.

    1. lurker

      Re: Indentation

      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.

      1. Andy Mc

        Re: Indentation

        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....

      2. Thing
        Mushroom

        VI?

        Burn the witch!!

        1. lurker

          Re: VI?

          @Thing

          I sense a disturbance in the force. You are a user of the operating system known as 'emacs', I suspect? :) I understand that there are plans to add an editor to that, one day?

    2. Whitter
      Boffin

      Re: Indentation

      If you are three scope-branches deep or more in a single method, seriously consider refactoring the method to have a few clear-cut early returns at the top, or to call other methods / worker classes instead.

  10. Simon Harris
    Joke

    'The documentation adds: "Long, descriptive method and variable names are good." Just like its headlines, then.'

    Whereas the Reg programming style guide requires that method and variable names contain alliteration and dodgy puns.

    1. LinkOfHyrule
      Paris Hilton

      Dont dis El Reg!

      I use their new Objective Paris language for all my programming needs!

      IF (!fucked_up) 8=={

      Return ReallyRudy_greatSuck-cess;

      }==8

      It's a bit messy in places but sort of gets the job done - I think they are using it for the new digital dole cue system too!

      1. Graeme Sutherland
        Paris Hilton

        Re: Dont dis El Reg!

        Paris codes in VALGOL.

        http://esolangs.org/wiki/VALGOL

        1. LinkOfHyrule

          Re: VALGOL

          Everything I say as joke on these forums this week turns out to be true! First it was hackable smart toilets and now Paris based programming languages!

      2. Wil Palen
        Paris Hilton

        Re: Dont dis El Reg!

        IF (!fucked_up) 8=={

        heh I thought this was no start of a compound statement, but instead a single unhappy-face-smiley statement. As in

        IF (!fucked_up) 8=={;

        This makes the other unhappy face unreachable code though

    2. John Smith 19 Gold badge
      Happy

      "Whereas the Reg programming style guide requires that method and variable names contain alliteration and dodgy puns."

      Hey. No peaking at the page source.

    3. Fink-Nottle

      > the Reg programming style guide requires ...

      copious comments on subject matter unrelated to the code in question.

    4. diodesign Silver badge
      Boffin

      Re: Reg style

      "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.

  11. Bronek Kozicki

    can't be bothered ...

    ... to argue one way or another regarding tabs or braces location. I simply accommodate the local style whatever it might be, because inconsistent style is worst style of all.

    There is one exception though: "Long, descriptive method and variable names are ..." pure evil!

  12. XioNYC
    Coffee/keyboard

    So...

    ...how long until "--gray-lady", "--pink-paper", and "--phone-hack" styles are supported in GNU Indent?

  13. The Bit Wrangler

    FLAME WAR!!!

    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...

  14. HereWeGoAgain

    Er, no. An American misconception.

    "For decades, dour broadsheet the New York Times and its style guide have presided over the world of posh writing across the world."

    Those of us in the civilised world tend to use New Hart's Rules.

    1. Petrea Mitchell
      Headmaster

      Not even all this part of the world

      I was raised on Strunk & White, myself.

  15. Hungry Sean
    Happy

    and a word in support of oneliner ifs

    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.

    1. Richard 81

      Re: and a word in support of oneliner ifs

      When I were a lad we'd get the cane for writing "goto" on anything.

      1. Law
        Pint

        Re: and a word in support of oneliner ifs

        "When I were a lad we'd get the cane for writing "goto" on anything"

        A cane? LUXURY!! The best we could 'ope for were a rusty iron bar, and we'd be grateful for it too!

    2. Rich 2 Silver badge
      Flame

      ARRRGGGGG!!!!!!

      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!!!

      1. PerlyKing
        Stop

        Re: ARRRGGGGG!!!!!!

        "all functions have precisely one entry point. They should have only one exit point"

        That's a nice idea ... unless it results in all sorts of contortions to end up at the single exit point.

This topic is closed for new posts.

Other stories you might like