Slashdot Mirror


Best and Worst Coding Standards?

An anonymous reader writes "If you've been hired by a serious software development house, chances are one of your early familiarization tasks was to read company guidelines on coding standards and practices. You've probably been given some basic guidelines, such as gotos being off limits except in specific circumstances, or that code should be indented with tabs rather than spaces, or vice versa. Perhaps you've had some more exotic or less intuitive practices as well; maybe continue or multiple return statements were off-limits. What standards have you found worked well in practice, increasing code readability and maintainability? Which only looked good on paper?"

32 of 956 comments (clear)

  1. Re:braces by Splab · · Score: 3, Insightful

    Nice, embed php code within HTML. That's bound to be fun debugging. Having to skim through thousands lines of html to find some embedded control statement.

    And you complain about the placement of else...

  2. Re:braces by heffrey · · Score: 5, Insightful

    It doesn't really matter what you do, so long as everyone on the team does the same thing.

  3. developer buy-in by Dionysus · · Score: 4, Insightful

    Without developer buy-in, whatever coding standards you come up with will be useless. IOW, ask your developers to create the standard together.

    --
    Je ne parle pas francais.
  4. Re:Keep it simple! by bondsbw · · Score: 5, Insightful

    Make it "cut and paste" friendly, and as small as possible.

    That's a really bad idea. Cut and paste causes code cloning, which is among the most difficult maintenance problems.

    Code should be designed, when possible, in small chunks (methods, functions, etc.). This keeps the need to think about refactoring to a minimum, since the code is already factored. Well factored code has many other benefits, including easier-to-write unit tests and better understandability.

    I maintain software that was originally written by someone as a prototype and eventually given production status. 4 years later, I am still pulling bugs out that relate to code cloning. Think of the guys who will maintain your software, please.

    --
    All my liberal friends think I'm a conservative, all my conservative friends think I'm a liberal.
  5. Re:braces by __aapbzv4610 · · Score: 3, Insightful

    If you ask a bunch of 3 year olds which looks best, they seem to pick K&R and can point out the structure better than the extra line feeds or white space in other coding formats.

    Are you serious? if you're going to make a bullshit claim like that, you could at least try to fake a citation. a three year old isn't going to know what they're even looking at, let alone knowing how braces and whitespace are used to group code into logical blocks.

  6. Re:braces by DaveV1.0 · · Score: 3, Insightful

    Not them, and that is a good enough reason.

    --
    There is no "-1 offended" or "-1 you don't agree with me" mod options for a reason.
  7. Re:braces by thogard · · Score: 4, Insightful

    The code is important. The braces are syntactical sugar.

  8. Re:braces by __aapbzv4610 · · Score: 3, Insightful

    yes the code is important, but knowing what code gets grouped and being able to follow the flow is just as important.

  9. Re:braces by DaveV1.0 · · Score: 3, Insightful

    I do something similar, but put the braces at the same tab as the conditional.

    if(something)
    {
            do_something();
    }
    else
    {
            do_something_else();
            if(otherthing)
            {
                    do_otherthing();
            }
    }

    It just boils down to preference.

    --
    There is no "-1 offended" or "-1 you don't agree with me" mod options for a reason.
  10. GNU Indent by Jim+Hall · · Score: 3, Insightful

    At my first industry job (internship) I quickly realized their coding standards were very different from mine. So I spent the first 2 hours after lunch on day 1 with GNU Indent, working up a script that would convert my code into the company's coding standard for indentation.

    Let the tools do the work for you. Just don't forget to run 'indent' before you check in your code.

  11. Re:braces by TheRaven64 · · Score: 5, Insightful

    There are other good reasons for putting open braces on their own line. The biggest is that most coding conventions have a maximum line width. If you have an 81-character line, you need to break it. When you are scanning down the code, all you see is a line at one indent level followed by another line indented more - you need to read the entire line to tell whether it's the start of a block or not. With braces on their own lines you can tell just by visual pattern matching where every block starts and finishes.

    While I'm in holy-war territory, I'll also chime in on the tabs versus spaces argument. The tab character has a well-defined semantic meaning. It means 'indent this line / paragraph by one tabulator.' If you are indenting anything there is only one character you should be using - tab. It does not, however, have a fixed width, and should therefore never be used anywhere other than the start of a line or for aligning two lines. If you have to split a function across two lines, you should indent it like this:

    {tab}function(arg1,
    {tab}_________arg2,

    Then, no matter whether the person reading your code thinks tabs should be 1 or 8 characters wide, arg1 and arg2 will always line up. Sadly, vim does not have the ability to distinguish marks used for indenting and marks used for alignment and so this has to be done manually.

    --
    I am TheRaven on Soylent News
  12. Re:Keep it simple! by superid · · Score: 4, Insightful

    the most egregious bug I think I ever introduced was due to code cloning. It was awful. I did not bother to properly refactor (hey it was 12 years ago) and as a result we ended up with diverging clones that needed to be separately maintained.

  13. Correct focus by QuietLagoon · · Score: 5, Insightful
    What standards have you found worked well in practice, increasing code readability and maintainability?

    .

    Coding guidelines are typically justified because, as it goes, most of the time is spent fixing bugs in existing code than writing new code. The guidelines are needed because it helps others to come up to speed quickly while they try to figure out the code in which they have to fix the bug(s).

    I think that is the wrong focus, as it tends to reinforce incorrect behavior, i.e., the writing of buggy code.

    Coding guidelines should focus instead on the techniques that help reduce the number of bugs in code. How is that done? It takes someone (typically a senior person) looking at the the bugs that have been found in the code, categorizing their cause, devising a way to prevent those bugs from occurring, then putting that into the guidelines.

    Keep the focus of the guidelines where it should be: to increase the quality of the software.

  14. Re:Keep it simple! by StrawberryFrog · · Score: 3, Insightful

    The difference between ""cut and paste" friendly code" and "use Cut and paste" is the difference between "bake a nice cake" and "get obese and prone to illness".

    Code that is well-factored can be (incidentally) suitable for cut-and-paste, but using cut and paste is the problem.

    --

    My Karma: ran over your Dogma
    StrawberryFrog

  15. Re:braces by harry666t · · Score: 3, Insightful

    Braces, braces, braces... I code in Python, which seems to be the only computer language that got the braces right:

    if condition:
        statement1
    else:
        statement2

    That's it! No braces at all.

    Well, maybe except in dictionaries:
    mydict = {"foo": someObject,
              "bar": 42,
              }

  16. Re:braces by aj50 · · Score: 5, Insightful

    Bollocks.

    Draw your line from the closing brace up to the first line with any text on it, that line is the start of your block.

    Having your opening braces on an empty line might be more aesthetically pleasing but has zero advantage in making the code clearer.

    Either way, the most important thing is to have everyone do it the same way, every time.

    --
    I wish to remain anomalous
  17. Coding standards depend on the ecosystem by Shados · · Score: 3, Insightful

    Each language or environments have their own features, and require different standards. One of the big things is that hopping from one project/company to the other should be intuitive (something thats basically forfeited in environments such as C++, and accepted as to not be possible, more or less) When the language is mainly controled or orchestrated by a single entity (Sun for Java, Microsoft for .NET, etc), people should set aside their own opinion and stick to the main guidelines (and complete them for areas where the main design guidelines do not cover).

    So for example, in .NET, stick FxCop or Code Analysis on, disable the rules that aren't relevant to your company (ie: localization rules on an app that doesn't require them), and stick to that. C++/VB6/Java/Smalltalk conventions have no place in there, so leave em out.

    Same holds true for any other environment. Don't use VB6 conventions in Java/C++ (I know the thought alone seems mind boggling, but I've seen it countless of times....ugh!), and so on.

    The biggest issue with conventions is just that: people take conventions that are specific to one language/environment, and don't realise that they are, so they port them everywhere else, so you have a program in language X that literally looks like if it was written in language Y (and takes twice as much code, is twice as buggy, is half as readable...)

  18. A few anti-guidelines by Fallen+Andy · · Score: 3, Insightful
    write; multiple; statements; per; line; for; 300; chars;

    If it's assembler then write pseudo ADA comments which bear no resemblance whatsoever to the badly commented code following - Bonus points if the pseudo code itself has bugs...

    If it's Delphi code make all units UNITx, all forms FORMx and all variables equally inanely named - if it's good enough for most Delphi books then obviously it's the right way to do things

    Avoid function prototypes - if it was good enough for Brian and Dennis it's good enough for anyone

    Overload operators in surprising and pleasing ways, preferably so that "-" does bitwise set inclusion

    Use macros extensively (without ()() because everyone knows only losers need them).

    Mix tabs and spaces indiscriminately

    Pick at least *two* styles for braces - Bonus points for gratuitously adding them where they aren't needed - (to really make the reader happy use the "{" on next line style here)(extra points if you are mixing tabs and spaces)

    Use if (1==x) , (x==1) and just plain old if (foo) randomly to add variety

    Write big huge case (switch) statements spanning 5 pages because no one would possibly understand dispatch tables

    Seriously though, if you're programming anywhere you're expected to conform to the local customs, wacky and out of it or not. It's part of the adaptability expected of a programmer...

    Andy

  19. Re:braces by Southpaw018 · · Score: 4, Insightful

    That's what you're SUPPOSED to do. The real world would rather have absolutely nothing to do with any of that.

    In my short experience in the workin' world, I've come across some pretty spectacularly awful implementations of everything under the sun, from production boxes in shambles to network cables wrapped around sweaty water pipes to 2 year old production code passing GET strings straight to the SQL server unmodified (yay nonprofit sector!), and compromising code for a quick and dirty webpage so I can get things running just a bit faster is 1) the least of my worries and 2) a metric fuckton cheaper than new servers (yay nonprofit sector!). :)

    --
    ACs are modded -6. I don't read you, I don't mod you, I don't see you. Don't like it? Don't be a coward.
  20. Re:braces by oddsends · · Score: 3, Insightful

    Now tell me, those studies refer to the readbility of the english language, not a given computer language, right?

  21. Re:braces by Anonymous Coward · · Score: 4, Insightful

    Idiots who think like this write code that has to run every day, using the previous day's output as input, and takes 28 hours to run.

    They think that you can have a baby in one month if you just put more men on the job.

    You can't always "put more men on the job", and you want to write code that puts out web pages responsively. Some times algorithms are the key to page performance, and sometimes, it is just coding practice.

  22. Re:Some of those examples by Maxmin · · Score: 4, Insightful

    "no NO!! Must not put elses near braces, my precious!" - Larry Wall

    I, for one, have never understood Larry's War on Cuddled Elses. It's almost symptomatic of OCD.

    Besides, how is the "else" getting "lost?" I mean, it's only two characters from the left margin! Saves lines too.

    Maybe it's that I prefer reading source that is not so vertically spread out. The more code and logic on the screen, the better. Density factor.

    --
    O lord, bless this thy holy hand grenade, that with it thou mayest blow thine enemies to tiny bits, in thy mercy.
  23. Re:Some of those examples by CastrTroy · · Score: 4, Insightful

    I like the braces on separate lines also. Makes things a lot more readable. Another good idea is to always put the braces in, even when you are only writing a single line. That way when somebody goes to put more code in the if statement, they don't have to remember to add them.

    --

    Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
  24. Re:Some of those examples by bperkins · · Score: 4, Insightful

    So we have a shop that has a whole lot of perl code and they're sent around this book as well as run perlcritic on our checked in code (which pretty much everyone ignores).

    In my couple of years there I've learned a few things.

    1) No one can agree on coding standards

    2) What people can agree on is so watered down that it's not very useful.

    3) The stuff that really causes headaches isn't bad style, it's general insanity. Hardcoded constants and poorly thought out ad-hoc parsers and general brain damage causes a million times more problems than just about anything anyone can describe in a standard.

    That said, in my experience the one thing that almost aways saves me time for anything larger than a couple of lines is to use "use strict."

  25. The Most Important Rule by harlows_monkeys · · Score: 3, Insightful

    When doing maintenance on someone else's code, use their style, even if it is one you hate.

  26. Re:braces by D-Cypell · · Score: 3, Insightful

    I am really sorry, something else you can learn from me is to always use the preview button :).

    The preamble was a little bit of waffle anyway... the important point...

    All significant performance problems in software are architectural in nature.

    You should be coding in the most easy to maintain style. Doing something difficult to maintain (like breaking MVC by merging controller logic into the view) might save a few milliseconds here and there. You will be quite proud of this until someone with more experience comes along and drops in a second level cache or adds some database indexes and increases performances by two orders of magnitude.

  27. Re:Some of those examples by Doctor+Crumb · · Score: 4, Insightful

    Density is the opposite of readable and maintainable. One of the main aspects of maintainable code is being able to find and change a single line of code quickly and without having to worry about breaking other nearby lines. Having more code per line means it takes that little bit longer to find and is that little bit riskier to change the one line of code. "Lost" in this case is only a minor delay, but when you add that delay up across several thousand bugs (i.e. any project in the Real World), it means you are wasting your time tracking down bugs in dense code rather than adding new features or working on other projects.

    Pop quiz: find and remove the bracketed clause in the above paragraph. Then think about how much faster you would have done that if it had been on its own line. Then think about how much faster you could have done that to 100 different paragraphs. It may not make a difference on the projects you work on, but in something the size of a perl interpreter or a web browser, it makes a huge difference.

  28. Re:Some of those examples by kramulous · · Score: 3, Insightful
    I don't know where I picked it up (Java ??!) but I pretty much always use:

    if (condition)
    {
    // something
    }
    else
    {
    // something else
    } // End of X branching

    I find that tracing parenthesis is a lot easier.

    --
    .
  29. Re:Some of those examples by telbij · · Score: 5, Insightful

    Density is the opposite of readable and maintainable.

    Bollocks. It's a tradeoff just like every other debate in the programming world. Sure, Perl gives you the ability to put way to much code on a single line. But the opposite problem of putting loads of white space all over the place is almost as bad.

    The more you spread out the code, the more you have to scroll. White space is valuable when it means something, like to separate discrete tasks within a long function. But the whole


    }
    else {

    thing is just a waste of space. It's one line less of code I can see. I visually parse } else { instantaneously. Similarly, some compound expressions or chained method calls make perfect sense. The right place to break out multiple lines depends on the reader's own cognitive abilities and familiarity with the symbols being manipulated.

    Otherwise
    writing
    like
    this
    would
    be
    much
    easier
    to
    read

  30. Re:Some of those examples by Maxmin · · Score: 4, Insightful

    My dear Doctor, readability metrics boil down to personal tastes - subjective, in other words. While perhaps what you choose is even the preference of the majority of coders, it's not mine.

    Advocating for braces and the negatory conjunctive "else" on the same line is not the same as "having more code per line," e.g. more than one statement per line.

    In the responses to the OP, we've if/else on three lines-

    if (...) {
    ...
    } else {
    ...
    }

    -and six lines-

    if (...)
    {
    ...
    }
    else
    {
    ...
    }

    Whilst reading six lines is not a problem for me, I prefer the three line variant, as it means less scrolling over slow ssh connections. Thank goodness we have automagic reformatting IDEs for those who won't accept other formats.

    However -- it is a sorry state of affairs that on /. the replies to an enquiry about "coding standards" end up focusing on code formatting... I'd much rather have been debating architectural design patterns as the response to "coding standards."

    Positions on design patterns, over the last few years, appear to have accreted into two clusters, those for and those against. I am one of those in the "for" camp, where learning the whys and wherefores of a particular set of data structures and classes, and behaviors arising from said structures, determine architecture.

    Those "against" appear, to my reading, to be willing to forgo such learning and accept whatever baked-in design patterns the platform's designers chose.

    Now, on the one hand, I accept that that's the case, as there is an observable stratification of programming ability existing in the world of software developers. One most go with one's strengths, and not everyone is suited to solving the issues architecture.

    On the other hand, if a developer is so inclined, there is still plenty of latitude available when structuring applications.

    Finally, there appears to have been a rise in the strongly anti-design patterns camp - the learning and applying thereof, that is. Most particularly, the anti-Java, pro-Ruby/RoR camp, where seemingly one must accept the baked-in design patterns chosen by the platform's architect, without variation.

    A direct descendent of that camp, the adherents to the prototype.js and scriptaculous libraries, accept the original author's patterns to the point where performance deficits due to overuse of lambda functions are not only accepted, they are ignored.

    That, IMNSHO, is sad comment on the state of software development. Productivity over performance is an awkward choice, to say the least.

    --
    O lord, bless this thy holy hand grenade, that with it thou mayest blow thine enemies to tiny bits, in thy mercy.
  31. Re:Some of those examples by Jesus_666 · · Score: 4, Insightful

    Funny? Insightful! Python is the language I would love to like.

    --
    USE HOT GRITS WITH STATUE OF NATALIE PORTMAN (NAKED AND PETRIFIED)
  32. Re:Some of those examples by telbij · · Score: 4, Insightful

    I've been a professional developer for 8 years and I've never spent significant time dealing with that bug. I'd rather have the code consistent than have it one way or the other. Developers have strong feelings about these things because of our attention to detail. But the sign of a good programmer is being able to say, "It's not worth my time to even think about this". If it was a clear win one way or the other then of course I'd get on board. But it's not. Being able to see more code on one screen has value.