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

23 of 956 comments (clear)

  1. Space Usage by Nerdfest · · Score: 4, Interesting

    I've worked where we were supplied a full IDE and a 17" CRT, and the coding standard forced so much white space vertically that you had to basically remember all the code.

    1. Re:Space Usage by Gorobei · · Score: 5, Interesting

      I've seen a number of private sector firms with coding standards. Some are just a few pages of common sense rules (naming conventions, etc) while others were book-length horrors created by people so incompetent that management didn't trust them to write code. I've seen requirements forbidding constants in code (correct practice was #define THIRTY_SEVEN 37, believe it or not,) and crazy Hungarian style naming conventions (nothing like several characters of line noise at the end of every function name.

      My current firm's approach is pretty simple:
      1. Write clear, understandable code
      2. Make it look like all the other code in our system
      3. Use the standard IDE
      4. The entire codebase is visible to all developers
      5. If you code does not conform, an annotated screenshot of it will be posted to our main developer chatroom
      6. People will then discuss your code publicly
      7. If the code is truly awful, a senior developer will declare it unacceptable, and delete it from the system

  2. braces by __aapbzv4610 · · Score: 3, Interesting

    I can't stand seeing the closing brace of an if statement sharing a line with an else, like so:

    if( condition ) {
        statement1;
    } else {
        statement2;
    }

    1. Re:braces by Dionysus · · Score: 5, Interesting

      If Kernighan, Ritchie, and Torvalds does it like that, who am I to do differently.

      --
      Je ne parle pas francais.
    2. Re:braces by tolomea · · Score: 4, Interesting

      I really don't get this obsession people have with putting braces on separate lines.

      Block scoping is perfectly well indicated by indentation and blank lines are valuable for dividing functional blocks of code.

      When you go and put all the braces on separate lines it totally kills the visual effect of the actually empty lines. Then you'll have to go and start using multiple blank lines for separating things and before long half the screen will be empty and mostly empty lines.

      Hmmm perhaps that's it, maybe this is a scheme for people who don't like looking at the code.

    3. Re:braces by Dachannien · · Score: 4, Interesting

      I don't like seeing opening braces sharing a line with anything else at all, unless the block gets closed on the same line.


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

      Yeah, it takes a bit more space, but I find it a lot easier to match blocks up when the braces are indented the same amount.

    4. Re:braces by __aapbzv4610 · · Score: 4, Interesting

      I keep braces on their own line when coding c++, but I do my indentation differently:

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

    5. Re:braces by fictionpuss · · Score: 5, Interesting

      Well, as long as we're admitting that "readable" is an entirely subjective experience.. I'd have to say that I would find that notation less intuitive than the "} else {" construct.

      It's too similar to consecutive 'if' statements which of course, breaks the logic.

      Also, extending your notation logic fully results in:

      if ( condition )
      {
              statement1;
      }
      else
      {
              statement2;
      }

      Which, although a waste of lines, is less confusing than your example.

    6. Re:braces by Southpaw018 · · Score: 4, Interesting

      That kind of code, when using PHP for templating, can make things much more efficient server side. Remember that anything within PHP tags is parsed by PHP. On a high volume site, even the relatively minuscule difference between passing something straight to the browser and echo("something"); can make a big difference in speed and resources.

      Besides, this is what syntax highlighters were made for. There are very good free ones on every single platform for a reason :p

      --
      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.
    7. Re:braces by Anonymous Coward · · Score: 3, Interesting

      That formatting doesn't follow the structure of the code. The else is not a new instruction, but a continuation of the if. It is "if condition instruction else instruction", not "if condition instruction" followed by "else instruction".

      An argument may be made for always putting braces on separate lines, but if you put opening braces on one line with the instruction, then the instruction should continue on the same line as the closing brace too.

    8. Re:braces by Glonoinha · · Score: 5, Interesting

      Ding ding ding - we have a winner.
      Real coders write code that you can take a ruler from any given close brace and draw a vertical line right up to the matching open brace, every time. Everybody else gets fired.

      Lines are cheap. Time added trying to figure out an obfuscated code structure because somebody wanted to save lines (ie, put the open brace on the same line instead of doing the above) is expensive.

      --
      Glonoinha the MebiByte Slayer
    9. Re:braces by gfxguy · · Score: 4, Interesting

      That's the way I've always done it, but it seems like most published coding standards don't like it.

      To reiterate: matching braces should line up horizontally AND vertically. It may "waste" lines, but the code is a lot more clear.

      I also, except in some cases (like some class getter/setter methods, where they're just all one after each other and it's obvious what they are), use braces even if it's a single statement that's being executed within. I don't see why code should be inconsistent just because it's a single statement that's being executed.

      I often get berated by other programmers for that style, but the only time I've applied for a job and had to stand at a white board and write code, and then describe my coding style, they seemed to appreciate it.

      --
      Stupid sexy Flanders.
    10. Re:braces by LuxFX · · Score: 4, Interesting

      I've always found this to be clearer.

      Drawing a line up to an opening brace doesn't tell you anything but the constraints of the code block, you then have to take another step to figure out what kind of code block it was.

      If you draw the line up to the first text line then you'll not only know the constrains but you'll know immediately without any further inspection if it was a for block, a while block, a function, etc.

      --
      Punctanym: alternate spelling of words using punctuation or numerals in place of some or all of its letters; see 'leet'
  3. JSF (Lightning II) coding standards by PsyQo · · Score: 5, Interesting

    I've always found the Joint Strike Fighter's coding standards document an interesting read. It is available from Bjarne Stroustrup's website (pdf)

  4. Serious != good by Exanon · · Score: 4, Interesting

    This sounds like a fairytale but I work for a very large IT firm which is very well known. Serious company doesn't mean good however.
    In certain files (not all apparentely) all constant variables have to be declared globally. We are talking C++ here.

    Think what you want, but I don't like it. The reason for the variables placements are so "that they will be easy to find".

  5. My new standard by thogard · · Score: 4, Interesting

    My new standard comes from a 1950's comp sci book.

    "Programs consists of input, output, processing and storage."

    Lose focus of that and the project will be late, over budget and most likely broken in ways no one will understand for years.

  6. precise spacing by griffjon · · Score: 3, Interesting

    One of my friends worked at a place where you'd have to insert whitespace to place certain elements (variables, evals, etc.) to begin at a specific col in the code within every line; in addition to standard indentation of the line. At one level, I see the concept, but seriously - highlighting and search is made to solve the same problem there.

    He left that job quickly.

    --
    Returned Peace Corps IT Volunteer
  7. Re:Well hungarian notation... by Lucas.Langa · · Score: 3, Interesting

    Also found I prefix in .NET really bad pracitce for marking interfaces like ICollection, what about when You decide turn interface to abstract class?..

    Well. The whole point of having interfaces is allowing the implementation of a certain method set to the world, which later can be used in your APIs using polymorphism. If you later decide to break the contract and make an interface a class, then probably a name change (made also automatically in tools like Eclipse or NetBeans) won't be any worse.

    As for the Hungarian notation, the standard form is indeed worthless. But we tend to use simple maximum three letter abbreviations of Swing components, to know that we are taking the username from txtLogin and listening for pressing btnOK. Code is more often read than written and this quasi-Hungarian style actually works pretty well.

    In fact, having interfaces named like "IPasswordProvider" is something very similar. It enables easy reading of your code and when you want to make a change, you instantly see that this type is an interface, therefore you cannot instantiate it directly, but you can implement this interface in any arbitrary class you may already have written, etc. Plus, Sun coding standards encourage you to name interfaces in a passive adjective way like "Serializable", "Comparable", etc. To comply with this format is not very natural for interfaces like "IPasswordProvider" or "IModelContext".

    --
    Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
  8. badness abounds in visual basic by hucke · · Score: 5, Interesting

    I worked for a company that was destroyed by a bad coding standard.

    This was a small company, that, back in '96, was awarded the contract for a POS application for a regional store chain, with back-office servers that would be updated nightly by modem.

    The guys who ran the company weren't programmers (though one of them knew enough to be dangerous); they were technical salesmen. They were also big fans of Microsoft, with "MVP" plaques on the walls, and every employee except me having Microsoft certs.

    I worked for them part-time while also working for another company. I advocated Unix (mostly BSDI and SunOS at the time), and always argued with them about why Unix was better (technical superiority vs. potential for big profits).

    When their big project was well underway, they brought me in to do the communications part of it, where the POS terminals would contact one of several servers by modem each night ("why not just ethernet them together, get a dialup PPP connection, and use IP? the interface is so much more reliable..." Request denied).

    The app was Visual Basic, with third-party "custom controls" for things like talking to modems. My part went fairly smoothly, and I was eventually asked to help out with the main application, which was suffering from unexplained crashes. When I looked at the code, I found something... strange.

    For error handling, they had elected to use a program called "VB Rig" (the name came from the rigging used on sailing ships, which prevents a sailor from falling to his death. Sometimes.) What this program did was to examine the source code, and then add error handling boilerplate at the start and end of each and every function. It inserted the exact same error handling code into every function.

    Because the error handler had to be all purpose, it was about 20 lines of code per function - sometimes much larger than the regular part of the function. And, worse, because it was the same for every function, and it made use of the same variable names, that meant either every variable had to be global, or you'd have to declare the ten or so standard variable names at the start of every function (they opted for the "everything is global" approach).

    Which led to things like this (forgive the syntax errors, it's been years since I've touched VB):

    On Error goto my_data_file_read_function_VBRIG_TRAP

    open MyDataFile for writing ...
    goto my_data_file_read_function_VBRIG_CLEANUP

    my_data_file_read_function_VBRIG_TRAP:
    on error 101 'Permission Denied
    delete MyDataFile
    resume
    on error 102 'File Not Found
    MessageBox 'Cannot read ' + MyConfigFile
    resume
    my_data_file_read_function_VBRIG_CLEANUP:
    blah blah
    my_data_file_read_function = SUCCESS ' return

    As you see, the error handling code - which had to be exactly the same for every function - made use of global variables (names like DataFile1, MyFile1, UserName, etc.) to figure out what to do for each error. That meant, that if there was any possibility you might have a "File Not Found", you had to expect the filename where that might happen to be in a particular global variable - say, MyFile1 - and hope that the calling function wasn't using that name too, for the same reasons.

    Naturally, files were being created and deleted at random, and the programmers often spent hours on the phone with the customer trying to figure out why the Access database had disappeared *again*.

    I asked if we could just write the error handling by hand, and use appropriate local variables; or take the standard VBRig error handling and trim out the lines that weren't relevant for a particular function (as subsequent VBRig runs wouldn't touch its code region if it saw that it had been customized).

    Request Denied. "This is our coding standard. We carefully reviewed the options before making the decision to use t

  9. Embedded Coding by JPEWdev · · Score: 4, Interesting
    I write code for embedded systems where there are many hundreds of C files that all need to compile together to form a single executable (everything shares a single address space). Since there are alot of modules working together, the most useful thing is the usage of prefixes for modules components. For example, all of the database public methods, defines, etc. are prefixed with a DB_ and all the private ones are prefixed with a db_. Granted, it is up to the programmer to enforce these restrictions, but it is nice to be able to tell exactly where a function comes from when reading through some else's code.

    On the strange side is the omission of vowels on functions and varible names to save text space (it's not required, but should be consistent for similarily names objects). It sounds weird, but is still quite readable.

  10. My workplaces' lovely standards... by Yosho · · Score: 4, Interesting

    multiple return statements were off-limits

    Despite the fact that it's not part of the coding standard where I work, I have a few coworkers who take this to the extreme. They surround every single function they write with:
    do{ ... } while(0);
    And then, inside the "do" block, they just put "break" in any place where they would have otherwise put "return." It drives me insane; they insist that having a single exit point from your function makes it easier to debug, but I just don't get it. I've never even seen them use gdb, anyway, so I think that abusing "printf" is their idea of "debugging"...

    One thing in our coding standard that I do like is that all variables that store units must have a unit specification at the end of their name -- in other words, all frequencies might have "Hz" or "MHz", distances might have "m" or "mm", times have "sec" or "msec", and so on. This is really helpful in my field -- it's not uncommon for me to open up a file that I've never looked at before and need to make modifications to it, and if the units everything things are stored in weren't immediately obvious, I'd have to go track down somebody and ask them. The annoying thing here is when people decide not to follow this standard because they think it should be obvious...

    --
    Karma: Terrifying (mostly affected by atrocities you've committed)
  11. Re:Some of those examples by laejoh · · Score: 5, Interesting

    Now that we're talking about 'languages that invite bad coding practices'... Well, one of the best programming books I've read is 'Perl Best Practices'. Not only does it list out best practices but it tries to explain (well I might add) why you should code a certain way and why other ways aren't good to follow.

    One of the habits I picked up from 'Perl Best Practices is:

    if (condition) {
    }
    else {
    }

    instead of:

    if (condition) {
    } else {
    }

    The else tends to get 'lost' when just following the closing bracket.

  12. Re:Some of those examples by xjimhb · · Score: 4, Interesting

    Why does everybody do it that way? That is, with the opening paren on the "if" line? I have always found that difficult to read. Why not

    if (something)
    {
        stuff
    }
    else
    {
        other stuff
    }

    or maybe even

    if (something)
        {
            stuff
        }
    else
        {
            other stuff
        }

    This last has always seemed to me to be the most readable, most obvious way to write the code. Can anyone explain why it is not used? (other than some well-known guru prefers the other?)