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.

Page:

  1. Jon Double Nice

    In Objective-C

    can't you imply/omit the curly braces using indentation after the if(), Python stylee? I quite like that.

    1. Frumious Bandersnatch

      Re: In Objective-C

      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!

      1. Fluffy Bunny
        Facepalm

        Re: In Objective-C

        Macro-expansion... that explains the superfluous use of braces. I'm too used to using modern programming languages like Java, Modula-2 and Pascal. I had forgotten how primitive C-based languages were.

    2. Ian Ringrose

      Re: In Objective-C

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

  2. Recaf

    4 SPACES?!

    Tabs! For the love of God, use tabs! What's wrong with people? Spaces indeed.

    1. Dr. Mouse

      Re: 4 SPACES?!

      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!

      1. Colin Miller

        Re: 4 SPACES?!

        Most editors can be set write out spaces instead of tabs, and to insert enough spaces to indent by 4 characters when TAB is pressed.

      2. Paul Shirley

        Re: 4 SPACES?!

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

        1. Flocke Kroes Silver badge

          Also defends against the else from the last if

          // 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();

          ········}

    2. rurwin

      Re: 4 SPACES?!

      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

      1. PerlyKing
        Mushroom

        Re: 4 SPACES?!

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

        1. Rukario

          Re: 4 SPACES?!

          Nope, on a VIC-20, you need colons.

      2. Brian Miller

        Re: 4 SPACES?!

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

        1. Phil O'Sophical Silver badge
          Happy

          Re: 4 SPACES?!

          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

      3. zanshin

        Re: 4 SPACES?!

        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.

      4. rurwin

        Re: 4 SPACES?!

        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.

      5. jorick

        Re: 4 SPACES?!

        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.

    3. Anonymous Coward
      Anonymous Coward

      Re: 4 SPACES?!

      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.

    4. Borg.King
      Pint

      Re: 4 SPACES?!

      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.

    5. Anonymous Coward
      Anonymous Coward

      Re: 4 SPACES?!

      Yes tabs are ideal and should always be used because they line up so nicely and leave lots of random gaps which make things look really neat and different in each editor.

    6. Gordon 11

      Re: 4 SPACES?!

      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.

    7. Anonymous Coward
      Anonymous Coward

      Re: 4 SPACES?!

      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.

  3. Tom 38

    Allman vs Whitesmiths

    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.

  4. Anonymous Coward
    Anonymous Coward

    "the leading brace on the same line as the if()"

    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.

    1. diodesign (Written by Reg staff) Silver badge

      Braces on separate lines

      Amen, brother.

      C.

    2. Steve Evans

      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!

      1. Anonymous Coward
        Anonymous Coward

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

    3. lurker

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

      1. rurwin

        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.

        1. This post has been deleted by its author

        2. the spectacularly refined chap

          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.

      2. Fluffy Bunny
        FAIL

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

    4. Steve Foster

      @Robert Long 1

      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.

      1. Richard 81
        Flame

        Re: @Robert Long 1

        Code style, shmode style. I vote "grokked" or "grok" or whatever be banned for ever.

        1. David Pollard

          Re: @Robert Long 1 @Richard #1

          "... grokked" or "grok" or whatever be banned for ever."

          No hols in Cornwall for you then!

          1. Sandtreader

            Re: @Robert Long 1 @Richard #1

            In Cornwall you'd be an emmet; grockle is Debon, me 'ansome.

            (anyway 'grok' comes from Heinlein = understand to a point of total immersion)

        2. Anonymous Coward
          Anonymous Coward

          Re: @Robert Long 1

          Read http://en.wikipedia.org/wiki/Stranger_in_a_Strange_Land - grok is one of the more appropriate tech borrowings from literature.

          1. Rippy

            Re: @sed gawk Re: @Robert Long 1

            > grok is one of the more appropriate tech borrowings from literature.

            This is a Brit site, right?

            Use the good newspeak word "bellyfeel": means the same thing, is patriotic, and has fifteen years seniority.

            G.

            1. Anonymous Coward
              Anonymous Coward

              Re: @sed gawk @Robert Long 1

              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.

      2. bigtimehustler

        Re: @Robert Long 1

        There is a reason in some languages, the following for example is valid in JS but is it really what you wanted to happen?

        return

        {

        a:"b"

        }

        or did you mean:

        return {

        a:"b"

        }

        Sometimes brackets do matter!

        1. Brewster's Angle Grinder Silver badge

          @bigtimehustler This old dog can't learn new tricks.

          That's gets me with amazing regularity and I fucking hate it! It is without doubt the worst feature in Javascript.

    5. Anonymous Coward
      Anonymous Coward

      It's not wrong at all. Just depends on your preference, as long as it's all consistent.

      1. richardcox13

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

    6. Number6

      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.

    7. Anonymous Coward
      Anonymous Coward

      My preference

      if(

      .......condition1

      ....&&.condition2

      ){

      ....action1;

      ....action2;

      ....etc;

      };

      (spaces/tabs rather than . obviously; the conditions line up with each other, the && or || etc appear to the left of the neat column)

    8. JP19

      Braces come in pairs and should be visually paired up by putting them in matching columns

      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.

    9. Frumious Bandersnatch

      Putting the first one at the end of the line is just stupid.

      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.

      1. Anonymous Coward
        Anonymous Coward

        Re: Putting the first one at the end of the line is just stupid.

        "Vertical space is precious when editing,"

        Firstly, it's a long time since I was last charged by the line, and secondly by that logic the closing brace should not be on a line by itself either.

      2. jorick

        Re: Putting the first one at the end of the line is just stupid.

        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.

        1. d3rrial
          FAIL

          Re: Putting the first one at the end of the line is just stupid.

          Every halfarsed compiler would shoot you to the moon for that, this is not an argument against using

          if(arg){

          ....doStuff();

          } else {

          ....doOtherStuff();

          }

Page:

This topic is closed for new posts.

Other stories you might like