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. tom dial Silver badge

          Re: ARRRGGGGG!!!!!!

          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?

          1. Paul Crawford Silver badge

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

        2. Rich 2 Silver badge

          Re: ARRRGGGGG!!!!!!

          There's nothing contorted about if()...

        3. jorick

          Re: ARRRGGGGG!!!!!!

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

          MISRA-C requires it!

      1. Paul Crawford Silver badge

        Re: ARRRGGGGG!!!!!!

        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!

    1. Kristian Walsh Silver badge

      Re: and a word in support of oneliner ifs

      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.

  1. Steve Knox
    Happy

    Excellent news!

    Now we good programmers have a resource to treat exactly as the good writers of the world treat NYT's writing style guide!

  2. Alan Bourke

    HERE IS THE ONE TRUE WAY

    If there's a house style around braces and indenting, then conform to that.

    Otherwise suit yourself as to what you find most readable, but leave other people's code alone.

  3. This post has been deleted by its author

  4. AlastairEB
    Facepalm

    Oh grow up...

    Style guide rules, to disagreement lead.

    Disagreement to anger leads.

    Anger, to the Dark Side leads!!

    ... (quoth Yoda, with a fine disregard for English syntax style guides)

  5. Flocke Kroes Silver badge

    There is always this polite and logically reasoned style:

    https://www.kernel.org/doc/Documentation/CodingStyle

  6. Chris Gray 1
    Facepalm

    Don't change TAB

    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.

  7. Martin
    Happy

    In C-style languages, should braces line up or not?

    Some strong opinions here in both directions.

    But let me just point out that Kernighan and Richie put the first brace on the same line as the if/while/for statements, not underneath it.

  8. graeme leggett Silver badge

    as a non coder

    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)

    1. Brewster's Angle Grinder Silver badge

      Re: as a non coder

      Programs are like diagrams; you can look at them and see what's going on. We can all read each others' coding styles, but a foreign coding style stops us absorbing the program until we have adapted; it's like trying to read a text in a really odd font.

  9. Luke McCarthy

    Good style guide

    I must admit I agree with pretty much all of it.

  10. Phill 3

    TAB - does what it says on the tin.

    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.

    1. This post has been deleted by its author

  11. Stilted Banter
    Headmaster

    Clueless in America

    All this just proves you should never take advice on style from Americans. These are people who insist on putting punctuation that doesn't belong there inside quotation marks And they write dates backwards. Ludicrous.

    1. Anonymous Coward
      Anonymous Coward

      Re: Clueless in America

      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.

      1. Stilted Banter

        Re: Clueless in America

        Agreed. Just backwards would be fine, but what they do is really dumb.

    2. Paul Crawford Silver badge

      Re: Clueless in America

      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.

  12. John Smith 19 Gold badge
    Unhappy

    I know this sounds dumb but..

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

  13. Herby

    One general rule:

    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.

  14. John Smith 19 Gold badge
    Happy

    Just realised we should call the K&R bracing style "biblical."

    For the first {

    shall be last and the last shall be first

    }

    That would have made things so much easier than it was.

    <sigh>.

  15. Anonymous Coward
    Anonymous Coward

    Use Python. The time you save ponderously arguing with your co-workers on code formatting can be, instead, spent on product delivery.

    1. Anonymous Coward
      Anonymous Coward

      Python, really?

      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.

    2. Anonymous Coward
      Anonymous Coward

      @AC 20:32

      Languages (like Python) that do not have static typing should never be used on projects that exceed 1,000 lines of code. There is a reason why they are called scripting languages.

  16. -tim
    Alert

    { has an ignored meaning

    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.

    1. the spectacularly refined chap

      Re: { has an ignored meaning

      It always introduces a new scoping level, even after an if. This isn't an ignored feature, it was discussed at length on comp.lang.c a few months ago.

  17. Steve I

    What about ME?!

    I tend to code using the 'Brush' font - neither tabs nor spaces work well...

  18. JohnMcL

    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.

    1. Brewster's Angle Grinder Silver badge

      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.

  19. Anonymous Coward
    Anonymous Coward

    Ctrl-Shift-F

    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?

  20. Anonymous Coward
    Anonymous Coward

    Haha, style guides.

    What happens is someone gives you the style guide with your first programming workpack and no time to read the fucker.

  21. rvt

    my favourite:

    Boolean someError=Boolean.FALSE;

    ..

    ..

    if (someError.toString().length()==5) return false else return true;

  22. BongoJoe

    Once up a time...

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

  23. btrower

    Spaces

    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.

  24. Sultitan
    Alert

    Braces bad, words good

    BEGIN da da da END - good

    { da da da } - bad

    in C use a macro to convert BEGIN to { and } to END and the eye strain almost goes away!

Page:

This topic is closed for new posts.

Other stories you might like