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

150 of 956 comments (clear)

  1. Some of those examples by AndGodSed · · Score: 4, Funny

    Sound an awful lot like coding in C... no bad coding practice needed...

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

    2. Re:Some of those examples by Bloater · · Score: 2, Insightful

      if your program looks like:

      if (sadf ~= /asdfijdfasd/) {
          dafdijseoifnjseoifjeasdpfjase;oifn
          a;seoifnmoeawnfsaoeinf
          a;seoifjas;oeinfaef
          as;efijesfoijes
      } else {
          lidnrglsodrnigas
          oihjesofnseoanf ;aiosejfo;saiehnf
      }

      like the typical perl program, then I can understand

      if it's C or C++ then

      if (a.is_good()) {
          a.modify_with(b);
          a.change_for(c);
          a.do_something_according_to(d);

      } else {

          a.report_error();
          b.report_unused();
          c.report_buggered(d);
      }

      It is a little less of a sensible rule. Coding standards will be peculiar to each languages idiomatic use.

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

    5. Re:Some of those examples by Zwicky · · Score: 5, Informative

      From a personal perspective that happens to tie in with the coding practices at my last company:

      The second example (GNU style) I have found to be quite cumbersome in writing, unless tabs are set to 2 with braces indented once and content twice (company mandated four with one indent for content in the block), in which case I would be frustrated with the extra keypresses involved.

      The first example (Allman style) I used to use until I moved over to Kernighan-Ritchie style (opening brace on same line as control statement, with functions (and classes in OOP languages) braces the exception; these are written in Allman style). This allows me to scrunch more onto the screen vertically.

      FWIW I never liked the '} else {' style of elses but at the same time, I never found it difficult to read so it was never a real issue. It makes sense to me to have the else begin at the same column as the if to which it belongs.

      This may be of interest to you.

      --
      "Three eyes are better than one" -- Lieutenant Columbo
    6. 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.
    7. Re:Some of those examples by Anonymous Coward · · Score: 2, Insightful

      I have a 14" screen on the computer I learned to program on. Extraneous junk on my IDEs took up anywhere from 15%-40% of the screen. As a result, I program concisely. I have an irrational fear of whitespace messing up my code, which results in a love/hate relationship with python.

      Also, one thing I've noticed is that when code is written:

      if (something){
            do_it(x, y, z);
      }

      The if clause is right above the start of the execution. It feels more solidly 'there' to me, because I see the whole block of code from the 'if' to the '{' as being the opening for the block. I don't see the '{...}' as being a way to force if() to regard the statement as one line, even though that's the case. I know you're supposed to program with lots of whitespace, but I've never liked it.

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

    9. Re:Some of those examples by peter+hoffman · · Score: 2, Interesting

      Thanks for the link!  I found a style there that appeals to me that I've not tried before which they say could be called "Lisp style" (with my slight mods here):

      for (i = 0; i < 10; i++) {
           if (0 == (i % 2)) {
               doSomething(i); }
           else {
               doSomethingElse(i); }}

    10. Re:Some of those examples by BronsCon · · Score: 2, Funny

      I think using python at all results in a love/hate relationship with python.

      --
      APK quotes people (including myself) without context and should not be trusted. Just thought you should know.
    11. Re:Some of those examples by gfody · · Score: 2, Insightful

      if vertical space is the issue, how about:

      if(something_is_true){do_something(); do_one_more_thing();}else{do_something_else();}

      That's pretty much what I see when I see open brace immediately trailing an if or else. I prefer open braces to line up with their corresponding close braces.

      --

      bite my glorious golden ass.
    12. Re:Some of those examples by lawpoop · · Score: 2, Insightful

      I think it's a matter of personal preference. I'm in the minority, and I guess it's for that reason that I hate being told that the other way is a standard. To me, the stand-alone brace seems to indicate that it's a stand-alone bit of code. But it's not; it's entirely dependent on the preceding else for its meaning and function. To me; it's less readable. It would be like having a comma or period dangling on a new line in a book. But it back up on the line where it belongs.

      --
      Computers are useless. They can only give you answers.
      -- Pablo Picasso
    13. Re:Some of those examples by kv9 · · Score: 2, Funny

      one true brace to rule them all, heathen!

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

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

      --
      .
    16. Re:Some of those examples by WK2 · · Score: 2, Informative

      That second one is often called the gnu style. Here are some reasons it is not used:

      1) It is cumbersome to write all extra those tabs.
      2) It uses a lot of horizontal space. Every indent is 2 tabs over. Nested ifs and fors and such will quickly approach the edge of the screen.
      3) It takes just as much vertical spcace as the Allman style, but the braces don't line up with anything at all.

      I find it odd that you refer to this as the most readable, most obvious way to write the code. Most people retch at the sight of it. To each his own.

      Btw, I haven't voted yet. I used to prefer the Allman style (largely because the first C++ book I ever read used it), but few projects use it, and several that I have worked with used the Kernighan-Ritchie style, and now I prefer it.

      --
      Write your own Choose Your Own Adventure. http://www.freegameengines.org/gamebook-engine/
    17. 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

    18. Re:Some of those examples by YourExperiment · · Score: 2, Insightful

      Looks to me like you should take up Python. :)

    19. Re:Some of those examples by Jesus_666 · · Score: 2, Insightful

      I was always under the impression that whatever the coder groks best is the most efficient style. People think differently and thus prefer different code styles.

      I think that having the opening brace on one line makes the block easier to identify as the conditional/method name/etc. looks similar to code; as my parse speed sometimes lags behing my reading speed I might overlook the beginning of an oddly-indented block. The additional linebreak is no problem because modern mice have scroll wheels and keeping long methods in mind is what short-term memory is for. That works well for me, but I have better short-term memory than most people.

      For you, keeping as much memory free as possible is more important than being able to identify a block without having to parse a line. Fine for you, but not universally superior.

      Most of these holy wars continue only because people forget that not everyone is the same and different people have different requirements. As in most cases there is no one-size-fits-all solution.

      --
      USE HOT GRITS WITH STATUE OF NATALIE PORTMAN (NAKED AND PETRIFIED)
    20. 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.
    21. 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)
    22. Re:Some of those examples by Samah · · Score: 2, Interesting

      At the place that I work, I got so sick of everyone's Java code being so lazily formatted (or not at all) that I FORCED people to code in a certain format. I configured the Eclipse formatter a certain way and made sure everyone on my team had it imported.
      Of course people can still be lazy and find it too hard to press Ctrl+Shift+F, but when I get given a code review, if they haven't formatted it, I instantly fail it.

      Some examples are:
      * Large chunks of whitespace between tokens (ranging from 0 to 3 spaces between an operator and a number/String in some cases),
      * Lack of or inconsistency of indentation using COMBINATIONS of spaces and tabs, and
      * Braces on the ends of lines in some places, and on the next line in others.

      Admittedly, programmers can be forgiven for messing up braces or whitespace occasionally (nobody's perfect), but when it's riddled throughout the code, it's time to hit Ctrl+Shift+F.

      --
      Homonyms are fun!
      You're driving your car, but they're riding their bikes there.
    23. Re:Some of those examples by Doctor+Crumb · · Score: 2, Insightful

      I would strongly suggest that you do the following instead:

      if (foo)
      {
      // block of code
      }
      else
      {
      // other block of code
      }

      The reason being that I can look at either the start or the end brace, and simultaneously see the matching brace without having to scan sideways or otherwise dig through extra code. Or if I wanted to change the else to an elseif, I could just move to the end of that line start typing, without worrying about having to go back 2 characters or otherwise avoid clobbering the brace.

      To take the example further, let's say the block originally looked like:

      if (x > 2) {
      // do stuff
      } else {
      // do other stuff
      }

      And Joe Newbie changes it to:

      if (x > 2) {
      // do stuff
      } elseif (x > 3)
      // do other stuff
      }

      Spot the bug. Putting the braces on their own lines prevents this sort of stupid mistake (and it *is* stupid, I agree, but it is also common). Sure, it's not that hard to find/fix once you hit compile, but wouldn't you rather be spending your time tracking down the interesting bugs than dealing with stupid bugs like this?

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

    25. Re:Some of those examples by fishbowl · · Score: 2, Insightful

      >Density is the opposite of readable and maintainable.

      Children's books, aimed at a young comprehension level, are written with 8 or 10 words per page.
      Do you prefer this format to one aimed at a higher level of comprehension?

      Here is your argument for "density" then.

      --
      -fb Everything not expressly forbidden is now mandatory.
    26. Re:Some of those examples by totally+bogus+dude · · Score: 2, Informative

      Hmm, it looks to me like the main difference w.r.t. readability is that you added an extra blank line before and after the else in the C/C++ version, which you didn't have in the Perl version. That makes it stand out quite a bit.

      I also much prefer aligning the {}'s vertically.

    27. Re:Some of those examples by Rysc · · Score: 2, Insightful

      Density shmensity.

      if( denotes the beginning of the conditional
      } denotes the end
      } else means it continues instead of ending

      So.

      if(...){ // begin ... // do stuff
      } // end
      else{ // what? ... // uhm
      } // end again?

      Confusing! What's that dangling else doing there? Sure looks funny without its friend the }.

      Those arguing in favor of braces on their own lines are usually obsessed by this kind of non-issue. They write like this:

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

      Which is even less readable.

      Now every person is different and sees things differently. I find it useful to put empty lines between sets of unrelated code, just for the very reasons you cite for putting } on its own line. Some people criticize that practice for a variety of reasons, but it works well for *me* and makes it easy for *me* to find what I need to find quickly. I happen to think it makes the code clean and maintainable, just as I think that } else { does.

      JAPH.

      --
      I want my Cowboyneal
    28. Re:Some of those examples by eclipser13 · · Score: 2, Informative

      Preferences -> Java\Editor\Save Actions -> Check "Format Source Code" Go around and smack people until they set that option and you'll never have to worry again. Anytime they do work, it will automatically format for them when they save.

    29. Re:Some of those examples by pablo.cl · · Score: 2, Informative

      Actually, reading in columns is easier than in long lines. Most papers use several columns and many blogs use an artificially narrow column.

    30. Re:Some of those examples by mazarin5 · · Score: 3, Funny

      Spot the bug

      The elseif block never runs, even if you put the brace back in? :)

      --
      Fnord.
  2. 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 Tony+Hoyle · · Score: 4, Funny

      Nah me neither... maybe it's a US thing? It's generally assumed that if you're a half decent programmer you'll follow what is already there and write clear concise code as much as possible.

      One place I was in did try to come up with a coding standard, but it was abandoned as nobody could actually agree on much other than 'don't fuck it up'.

    2. Re:Space Usage by LordOfLead · · Score: 5, Informative

      The Linus says:

      "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program."

      from http://en.wikiquote.org/wiki/Linus_Torvalds

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

  3. 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 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 __aapbzv4610 · · Score: 3, Informative

      yes, putting the else on a new line makes it a bit more readable; you know that line marks the beginning of an else:

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

      reading this kind of code tells you that there is an else condition there. having a leading closing brace makes you have to read into the line to see what's going on. I know it's 2 characters, but when scanning code for structure, it helps to have it on a bew line.

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

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

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

    7. Re:braces by LEMONedIScream · · Score: 2, Insightful

      I see your quotes but this whole idea of one being better than the other is asking for a fight.

      I find it much easier if you're happy to easily switch between whatever people want (within reason). As a Computer Science student, seeing how difficult it is to read code not in a format I usually write, why would I want to make it harder for the person marking my work?

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

      unless you're using a 12 inch monitor, they extra lines aren't really hurting anything. braces show where code blocks are, and blank lines are used within those blocks to break up the code into logically separate blocks.

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

    10. 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.
    11. Re:braces by thogard · · Score: 4, Insightful

      The code is important. The braces are syntactical sugar.

    12. 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();
      }

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

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

    15. 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.
    16. Re:braces by Anonymous Coward · · Score: 2, Insightful

      If the PHP is for presentation, yes, that should be where it goes. Further, if you have a thousand lines of HTML, you're doing it wrong. Would you prefer they embedded the HTML way back in the logic? try finding THAT and changing it.

    17. 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.
    18. Re:braces by fictionpuss · · Score: 5, Funny

      True - but at least it keeps thousands of otherwise dangerous PHP developers safely occupied.

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

    20. 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
    21. Re:braces by TheRaven64 · · Score: 2, Interesting

      Maybe the way you code, you never have a line that is so long that it needs to be broken. In most C code I've seen (and all C++ or Java code) a lot of lines exceed the 80-column width that is a common maximum for coding conventions. You then can't clearly distinguish between the start of a block and a wrapped line without clearly inspecting the indenting. This is even more true in Objective-C, where long methods are often written with one parameter on a line.

      --
      I am TheRaven on Soylent News
    22. Re:braces by tolomea · · Score: 2, Insightful

      "braces show where code blocks are"

      Like I said, "Block scoping is perfectly well indicated by indentation"

      You are indenting stuff correctly and consistently right? cause if your not then talking about any other aspect of code formatting is a waste of time.

    23. 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
    24. Re:braces by Splab · · Score: 2, Insightful

      NO! NO NO NO no no no no NO!!!!

      You simply do NOT compromise your code for "efficiency" when you are already running a script language. Any web site is extremely scalable, when you grow you just plug in more servers, at some point your database can't handle the load so you start caching your pages, then you add more servers etc.

      You never EVER compromise your code for efficiency when you can get 100 times more bang for the buck by adding additional servers.

    25. 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,
                }

    26. Re:braces by thogard · · Score: 2, Insightful

      The 3 year olds were at test at Stephens College (Columbia Mo) in their preschool education classes around 1986 or so. There are published papers but I've got no idea where to find them to cite them.

    27. 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.
    28. 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
    29. Re:braces by tolomea · · Score: 2, Insightful

      24" dell lcd's cost $350, that's in the neighborhood of 1 days pay and they are good for a couple of years, I make a point of not working anywhere that can't figure out that a decent screen will cumulatively save me at least 1 day over it's lifespan

    30. Re:braces by Rakshasa+Taisab · · Score: 3, Funny

      Yes I totally

          agree,

      It is

      so much better to

          put

              a lot of vertical

      space

          between lines.

      --
      - These characters were randomly selected.
    31. 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'
    32. 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.
    33. Re:braces by KostasPlenty · · Score: 2, Funny

      The code is important. The braces are syntactical sugar.

      Guido van Rossum is that really you?

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

    35. Re:braces by russotto · · Score: 4, Funny

      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.

      Messrs Kernighan and Ritchie and their no-necked associates would like to have a word with you out back.

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

    37. Re:braces by orlanz · · Score: 2, Interesting

      Oh GOD, both of your examples are such waste of visual real estate. I understand that its no longer worth as much as it used to be, but come on, show some respect for... the environment and all that.

      I would write that as:

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

      But yes, it does boil down to preference and my formatting would change to the else style if there were multiple/long lines. ^_^

    38. Re:braces by mikael · · Score: 2, Informative

      That is the Indian Hill C Coding Standard. It is almost mandatory to learn for certain areas of computer programming such as device driver development and applications programming. Mainly because it is the first documented coding standard that came out and was used by universities and corporations.

      I've known some companies to make it a priority that all programmers used this standard when their greatest threat to survival was keeping up technologically with their competitors.

      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    39. Re:braces by Haeleth · · Score: 4, Informative

      Like many Python evangelists, you seem to have a remarkably limited experience of computer languages.

      Here's a language with no braces:

      IF condition THEN
          statement1
      ELSE
          statement2
      ENDIF

      Here's another:

      (cond (condition statement1)
            (t statement2))

      Here's another:

      if condition then begin
          statement1;
      end else begin
          statement2;
      end;

      Here's another:

      if condition then
        value1
      else
        value2

      or, more extensibly,

      match condition with
        | true -> value1
        | false -> value2

      And the list goes on. Maybe you should try learning some other languages. Broaden your mind a bit. There's a lot out there that isn't Python or C/C++/Java. Some of it is quite interesting.

    40. Re:braces by maxume · · Score: 2, Funny

      Twitter would like to hire you, so that they can go on to fire you.

      --
      Nerd rage is the funniest rage.
    41. Re:braces by Bloater · · Score: 2, Funny

      Coders that write code that needs a ruler to find the start of a block get fired much more frequently than those who don't. How many inches is the ruler you use? More than one and something is very wrong.

      All these formulaic alignment and whitespace techniques are workarounds for the fact that your code is too complicated and not structured enough.

    42. Re:braces by sideswipe76 · · Score: 2, Insightful

      OK, I have to put in on this. This whole 80 character line length is arcane bullshit. 80 character line lengths come from the time of C programming, mainframe punch cards and vt100 displays. Mainframe punch cards had a maximum length of 80 chars. vt100 and VGA disaplays were 80x60 displays and so it made things easier. At the time, many compilers couldn't handle more than 80 char lines. Fast forward. In java today you have: public static synchronized List > getSomethingStupid( Map >, Set >) throws LifecycleException.Fatal, IOException { Don't be a tool. With all the exceptions, qualifiers and generics being used in modern java an 80 character line length is not only a relic of the past, it's counter productive because it produces utterly unnatural code. Oh, and PS, my 1280x768 display can handle a bit more than that Rest assured your compiler can handle it. You might say: Well, that is just poorly written code. I would agree, but it's code that's 1) legacy or 2) written by one of my current teammates who is far too impressed with his 2 years of experience and degree from an overpriced university. As it is written by someone self important that I work with I have to simply deal with it since I can't just bitch slap him. tabs v spaces -- I don't care; my editor displays both nicely. Curly brace on same line as method signature. Again, don't care. All of that I have gotten use to in 10 years. It wasn't until I got to the team I am on that bad code, self-importance AND 80 character Nazis all got rolled into 1 code base.

    43. Re:braces by WGR · · Score: 2, Insightful

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

      So you have several million bucks to pay the damages for a personal information breach.
      Then why are you still working as a programmer?

    44. Re:braces by harry666t · · Score: 2, Interesting

      I think I can see Lisp, OCaml, probably Modula-3, there's one example I think I saw before, but can't remember the name...

      I grasped a bit of Python, C, C++, Java, Perl, Bash, PHP, and a little of Smalltalk, D, Common Lisp, Ruby, Pascal, x86 assembly and z80 assembly. I was always interested in various computer programming languages, trying to write just a few lines in about every single one for which I didn't had trouble with getting a compiler. Even before I knew anything but C, I tried to create my own syntax using the C preprocessor #defines (replacing "if(" with "IF", "==" with "IS", etc). I wrote my own toy z80 assembler, tried writing a custom shell. For the purpose of my toy project involving genetic algorithms "research" (just curious if it could spit something interesting out) I've also "created" a "language" based on lists and objects rather than some text representation. I have a few random drafts of my own OO language, hidden somewhere at the bottom of a drawer.

      I think that this makes a decent list for a 19 year old who learned to program in his free time, while also having a normal life and OMG, devoting most of the aforementioned free time not to coding, but to playing lead guitar in a progressive metal band without a name. But that doesn't actually matter...

      Well, yes, in my previous post, I might have sounded like an ignorant troll. We all make mistakes, sometimes dumb mistakes that make us look like ignorant trolls, but isn't this whole "life" thing all about learning from these mistakes?

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

    46. Re:braces by kv9 · · Score: 2, Funny

      However, I don't know anyone else in the Universe who codes like this, and I can't figure out why.

      they all got shot.

    47. Re:braces by wkitchen · · Score: 5, Funny

      YOU FORTH LOVE IF HONK THEN

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

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

  6. It's easy by krkhan · · Score: 5, Funny

    First off, I'd suggest printing out a copy of the /. comments, and NOT read it. Burn them, it's a great symbolic gesture.

  7. Well hungarian notation... by Anonymous Coward · · Score: 2, Insightful

    is classic one - brilliant example of really harmful coding standard. Especially after Years of refactoring, where wParam doesn't mean WORD anymore...

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

    Generally embedding some semantic value into the syntactic is IMHO really bad practice.

    Well, also used to work in company which decided to use Capiltalized names in Java, so instead fo getFoo, they decided that is much cleaner to have GetFoo. Of course ta the same time, the company had to accept that half of the Java frameworks, following JCS didn't worked for them...

    lima

    1. 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.
    2. Re:Well hungarian notation... by Anonymous Coward · · Score: 2, Informative

      wParam

      You were doing it wrong. The compiler knows it's a fucking word or long int or whatever, use the prefixes to encode something the compiler DOESN'T know about.

    3. Re:Well hungarian notation... by hedronist · · Score: 5, Informative

      Strangely enough, Hungarian worked quite well for the problem it was originally intended to solve.

      I worked at Xerox in the late 70's and my manager was Charles Simonyi, inventor of this notation. The project was BravoX (grandparent of MS Word) and was written in BCPL. BCPL basically has one type: integer. How that integer is treated is purely a function of how you reference it. E.g. fooFirst>>fooNext means "use the variable 'fooFirst' as a pointer to a structure of type FOO, one of whose elements is (from the naming convention) a pointer to some other FOO." Whereas fooFirst+1 adds one to an integer and (almost certainly) yields an invalid point that bill blow up when you try to use it. (It's been 30 years since I wrote anything in it, so I probably screwed up the example.)

      Since there was only one type, the compiler didn't/couldn't perform type checking. Hungarian was a way of putting the type into the name of the variable so that the programmer could perform visual type checking. There were 9 of us on the project and the consistency/readability across the code base was impressive. Any of us could go into anyone else's code and almost immediately see what was going on.

      I still use a light variant of it in my own code, but when in someone else's code I try to stick to their naming/formatting convention.

      Like so many good ideas, it worked well in its original context but became twisted out of shape when used for something never intended/envisioned by the original developers (even though the person doing the twisting was, in fact, the original developer!). Another example of this is the Third Eye Software symbol table format I created for my debugger, CDB, but which was then used and abused by Mips to create a complete piece of crap. What they did still has people swearing at me 20+ years after the fact. (More on this at Third Eye Software and the MIPS symbol table)

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

    1. Re:My new standard by Southpaw018 · · Score: 2, Insightful

      Though this is technically OT, I think he's trying to restrict development to those elements. Alas, the real world doesn't quite work like that, what with office politics and policies and bosses and humans being, you know, humans.

      --
      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.
  9. [Java] Use Checkstyle by Lucas.Langa · · Score: 5, Informative

    If you are using your computer right, it does not only enable you to do things, it does the boring things for you, automatically.

    Checkstyle is one of the tools in a company toolkit that is often overlooked but in fact VERY handy. It enables you to define a ruleset for your source code, finding stuff which is incompatible with the coding practice in your company/team/project/whatever. Moreover, you can stick it into Eclipse using the free Eclipse-CS plugin, so it will automagically mark the places which need to be change. Last but not least, you can put Checkstyle as an Ant task in your building environment (and in your continous integration toolkit) so commited code that does not conform certain standards does not build.

    As for the rules themselves, we've found these to be the most successful:

    • limit the length of the method to be visible on one 1280x1024 screen; if it's longer it's probably handy to extract smaller methods from it - which will be far more easy to read
    • similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)
    • an upper limit on the allowed number of method parameters seems to be a good idea as well
    • ensure that new code is commented by marking structures which could be javadoced but aren't
    • any naming and formatting convention is better than no convention; Checkstyle can use regular expressions to validate type, variable and other names. It can also check for whitespace constraints, new lines, etc.
    • avoid star, redundant and unused imports
    • enforce or forbid the usage of the tabulator character to have all code clean no matter where you open it
    • warn on redundant modifiers
    • enforce the usage of braces everywhere (e.g. disallow if (something) action; ): no misformatting will hide a trivial but dangerous bug
    • a major one: Checkstyle can warn if it discovers a typical coding problem (of course this has some false positives but better to be on the safe side): double checked locking, lack of hashcode when overriding equals, switch fallthroughs, illegal catches and throws, lack of super.clone() or super.finalize(), etc.
    • you can also constraint the number of returns from methods (we found it to be very useful to set this to 1, using a result variable everywhere else - it's far easier to get hold of the code flow then)
    • we also constraint the if depth and boolean expression complexity to manage the cyclomatic complexity - also for easier reading
    • it's useful to make Eclipse clean up your code on every save: to add "final" where it can, to fix imports, format the code to the specified form, etc.

    Of course, we let developers to add suppresions for the 1% of false positives. In fact, there are very few suppresion rules set.

    --
    Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
    1. Re:[Java] Use Checkstyle by Lucas.Langa · · Score: 2, Informative

      Even here you see why people hate coding standards.

      avoid star, redundant and unused imports

      This only impacts build time. Not worth the time and hassle of importing every class individually for saving an additional 90 seconds on the rare occasion you do a complete rebuild.

      The point of avoiding stars, redundant and unused imports is to enable readers of a particular class to easily see the dependencies of this compilation unit. When you have an arbitrary nonsense dependency which is not used, and your class has a couple of hundreds of lines of code - the reader will have trouble finding this fact. Have in mind that he/she could read your code by literally printing it out (many people still hate reading and inspecting things on CRT/LCD monitors).

      Your point seems to be that it's better to import the whole classpath and do not have to think about it. But in fact, when you're coding using Eclipse or NetBeans, the imports are cleaned automatically for you.

      enforce the usage of braces everywhere (e.g. disallow if (something) action; ): no misformatting will hide a trivial but dangerous bug

      Stupid, forcing braces makes some code more unreadable. Situations where it's inappropriate to omit them can be caught during code review.

      Seems to me you like to manually do things which can be automated. Having obligatory braces really reduces the percentage of problems like "Did you mean both lines should be in the else clause?" "Heck, I don't remember - let's waste time on it and find out." or "Sorry, I really thought there were braces where I put my extra line while refactoring..." See, we've been here before and this simple rule solved all these things.

      The other thing I disagree with is that braces make code unreadable. In fact it's pretty much the opposite, if you use any reasonable formatting style while coding. Making braces obligatory makes the code very predictable.

      Plus, just to repeat my mantra again: putting missing braces in if / else clauses can be automated in IDEs like Eclipse or NetBeans.

      --
      Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
  10. 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.
    1. Re:developer buy-in by Minwee · · Score: 5, Funny

      ask your developers to create the standard together.

      Why don't you just give them all giant Q-tips and play the Star Trek fight music every time they meet?

      Surely that would be at least as productive as asking them to all agree on coding standards.

  11. 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.
  12. 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
  13. 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.

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

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

    1. Re:badness abounds in visual basic by Splab · · Score: 4, Funny

      I love abbreviations, not being native English speaker I used to think POS was "piece of shit" since its usually being used when talking about software (failed software).

      (Or the always common "IANAL", well good for you buddy, but we are talking about legal issues here - the arse pounding is for when you get behind bars)

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

    1. Re:Correct focus by pz · · Score: 2, Insightful

      I wholly agree, and find that Conway's "Perl Best Practices" does an excellent job of just this, for people who are writing Perl. In the book, Conway goes through a number of different options and describes why they're just bad ideas, arguing mostly from a maintenance and clarity perspective, and cogently suggests superior options.

      --

      Put my fist through my alarm clock with its ding-dong death inside my ear. - The Blackjacks.
  17. 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.

    1. Re:Embedded Coding by trompete · · Score: 2, Insightful

      We do the inverse as far as capitals, but we also use the "static" modifier to make sure nobody tries to call the function from another file.

  18. Re:Keep it simple! by StrawberryFrog · · Score: 4, Informative

    There are several tools that can detect cut and paste code:

    Simian: http://www.redhillconsulting.com.au/products/simian/
    PMD: http://pmd.sourceforge.net/
    DuplicateFinder: http://www.codeplex.com/DuplicateFinder

    And probably others

    --

    My Karma: ran over your Dogma
    StrawberryFrog

  19. Re:Some stuff that was stupid by jrumney · · Score: 2, Insightful

    3. You will put the constant on the left for comparisons. This one isn't bad in and of itself, it's an =/== fix...

    Every compiler made in at least the last two decades has a warning for the same purpose. This type of unnatural ordering of comparisons to force compiler errors where an equals sign is left out usually signifies a code base that is in such a bad state that the developers turn off or ignore compiler warnings.

  20. Re:Keep it simple! by 4D6963 · · Score: 5, Funny

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

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

    Wait.. are you trying to say that copying the same lines of code over and over again must be avoided? So tell me genius, how else would you implement such a function without copying?

    int multiply(int a, int b)
    {
    int x=0;

    if (a==1)
    {
    x+=b;
    }

    if (a==2)
    {
    x+=b;
    x+=b;
    }

    if (a==3)
    {
    x+=b;
    x+=b;
    x+=b;
    }

    // Damn lameness filter, wouldn't let me paste my code in the entirety of its 132,356 lines

    return x;
    }

    --
    You just got troll'd!
  21. 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

  22. No standard is a good standard by khendron · · Score: 2, Insightful

    I've come across, been subject to, and written many coding standards during my career and have come to the conclusion that coding standards are, for the most part, useless.

    It is much better to let coders program to whatever style they are most comfortable with. Forcing specific bracing and indentation styles just leads to ill-will from most coders and creates a bureaucratic overhead that is more more trouble than it is worth. As long as the style is consistent within a single file, most programmers will have no trouble following it and have no trouble maintaining the code.

    The only standard I think is worthwhile, when coding API libraries and such, is a naming standard. For example, a coder should not have to guess whether the method to get a property value is getProperty() or property_get() or propertyValueOf() or whatever. I don't care what the naming standard is, as long as it is consistent across the API.

    --
    Life is like a web application. Sometime you need cookies just to get by.
  23. Re:Hungarian notation by zm · · Score: 2, Interesting

    Apparently, the bastardized version of Hungarian Notation got popular: http://www.joelonsoftware.com/articles/Wrong.html

    zm

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

  25. 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)
    1. Re:My workplaces' lovely standards... by TheRaven64 · · Score: 2, Interesting

      Your comment leads me to a meta-comment. Any coding standard should (must) justify any decisions it makes. Any coding standard guidelines that don't come with a justification are just cargo-cult programming.

      There is a good reason for single-return functions. That reason is that it means that you can always put cleanup code at the end. You can do this with a big do ... while(0) block with cleanup code after the while, if you want. The compiler I just wrote actually does something quite similar - cleanup code goes in a block at the end and when you issue a return statement it sets a local variable and jumps to the start of the box. In a function with no cleanup code, however, there is no reason at all to avoid multiple returns, except that someone might later add a cleanup line at the end, expecting execution to always go there.

      If you are using a language with lots of non-local gotos (or, 'exceptions' as they are now known) then this doesn't make any difference.

      --
      I am TheRaven on Soylent News
  26. Coding styles useless without enforcement by Pedrito · · Score: 2, Interesting

    I work for a major software vendor. The particular group I work in wrote the application framework for a suite of apps. Our code is mostly quite nice. There were about 20 people working on it during development and there are a few pieces that are crap, but for the most part, it's quite well designed and written.

    Now, there are other groups that use this framework. One group in particular, has pretty much the same standards that our group does. The difference is, however, that their manager never had them do code reviews and so people pretty much ignored the standards. I've now been tasked with working with that group and their code is a complete nightmare. For example, a single form class with something like 16 tab pages (spread among 3 or 4 tab controls), over 200 controls, and over 9000 lines of spaghetti code.

    Had this group done code reviews, this class never would have passed, and it wouldn't be such a nightmare to deal with. At this point, we're already shipping the second version, so a complete rewrite of the various nightmare components of this app are out of the question, which is too bad because it's going to be a nightmare to maintain, especially when the guy who wrote it leaves.

    I've always hated doing code reviews, but this experience has made it abundantly clear to me how important they are for minimizing the damage a single clueless programmer can get away with.

  27. Style != substance by melonman · · Score: 2, Interesting

    I've never been convinced by any hard-and-fast coding stylistics. Sure, it's possible to write good code and bad code, readable code and unreadable code, but beauty is very much in the eye of the beholder, and, also, it depends a lot what you are trying to do. Insisting on one inflexible set of stylistics works about as well as telling people never ever to split infinitives or never ever to use the word 'said'.

    Last night I came across this in the documentation for CPAN's Net::Server (you probably guessed from the above that I'm not a Pascal programmer):

    You may get and set properties in two ways. The suggested way is to access properties directly via
    my $val = $self->{server}->{key1};
    Accessing the properties directly will speed the server process - though some would deem this as bad style. A second way has been provided for object oriented types who believe in methods. The second way consists of the following methods:
    my $val = $self->get_property( 'key1' );
    my $self->set_property( key1 => 'val1');

    This struck me as remarkably sensible - the author of the module puts his prejudices on the table, but tells you how to do it a different way if you like. (And, personally, I prefer the first example, because it's just as clear, faster, and I've never managed to take OOP in perl entirely seriously - a problem that Larry Wall appears to have too.)

    You judge good style in any particular case by looking at the overall work, not by nit-picking about the punctuation in isolation.

    --
    Virtually serving coffee
  28. Re:Keep it simple! by Haeleth · · Score: 5, Funny

    Duh, you so need to learn about this little thing called structured programming, which can totally help cut down on code duplication like that crap.

    Here's a hint:

    int multiply(int a, int b)
    {
        int x = 0;
      loop:
        if (!( a --> 0 )) goto done;
        x += b;
        goto loop;
      done:
        return x;
    }

    See? Much easier to understand than your spaghetti code, and much more maintainable too.

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

  30. Editing the minimum # of lines possible by MobyDisk · · Score: 2, Interesting

    Forget this pointless stuff about tabs and spacing, I've seen some really brain-dead policies.

    1) Source Control Substitute
    At one shop, there were designers who edited XML + image files (kinda like web pages, but not quite). There was a compiler that built this all into a single executable. They were not permitted to edit the source directly, and had to work on copies. And those copies must be on the network instead of their local drive. And source control was not allowed.

    So instead of people having local copies and then committing their work, everyone made a duplicate copy on the network for each thing they did. It took hours to make the copies, and the compile times went from a few minutes to 45 minutes. Plus, the network drive kept running out of space due to all the gzillions of copies of everything.

    2) Making the "minimal" change required
    I worked for a US government contractor and they wanted each change to have the minimal impact on the system that was possible. So, basically nobody ever removed code, only added. One time I encountered a huge nested if statement that spanned hundreds of lines. Upon looking at the cases, I noticed that many of them were the same. Like:

    if (a)
        if (b)
            do x
        else
            do y
    else
        if (b)
            do x
        else
            do x

    which can, of course, be simplified to:
        if (a and not b) do y else do x

    This was because people had to make the MINIMAL change required each time a change was made. And removing a level of the if statements was more lines of code modified than just changing "do y" to "do x"

    Imagine this, but with dozens of cases spanning hundreds of lines. I spent almost a day to build a chart listing what each combination of variables did, and finally chopped hundreds of lines of code to about 10 lines. Turns out that after years of changes, most of the cases now did the same thing.

  31. Re:Keep it simple! by Kihaji · · Score: 2, Interesting

    int multiply(int a, int b) {
    if(a == 0) return 0;

    if(a == 1) return b;
    else return b + multiply(--a, b);
    }

  32. Standards are important for shared projects by yelvington · · Score: 3, Informative

    Some programmers think they should be able to do anything they want.

    That might be OK if you live in your parents' basement and code for yourself, but in the real world it's a bad (and selfish) idea.

    Strict adherence to a standard is helpful in code review and in cases where a component is taken over by a new maintainer.

    This is always important, but it's particularly important in a genuinely open, community-driven project.

    The Drupal project is an example. It has a coding standard derived from the PEAR project that applies to any code submitted for inclusion in the core.

    Contrib authors are encouraged, but not required, to follow it. The good ones do.

    The Drupal Coder module does a very good job of nagging at you until you get the formatting right, and also helps with code migration and updating when the API changes. And it finds some common bonehead mistakes that can create security issues.

    Adhering to a standard doesn't have to be painful. Using a properly configured text editor helps. There is good support for Drupal standards and conventions in OpenKomodo and the commercial Komodo IDE, as well as some other editors.

  33. Re:braces && 3 year olds by sciop101 · · Score: 2, Funny

    The 3 year olds were at test at Stephens College (Columbia Mo) in their preschool education classes around 1986 or so. There are published papers but I've got no idea where to find them to cite them.

    These 3 year olds were given a 10 minute time out and a grape juicebox. During the timeout, the 3 year olds developed time travel, went back, deleted the test and grape juiceboxes.

    --
    The only thing new in this world is the history that you don't know.[Harry Truman]
  34. [C#] Use FxCop, StyleCop, Resharper by StrawberryFrog · · Score: 2, Interesting

    If you are using your computer right, it does not only enable you to do things, it does the boring things for you, automatically.

    Exactly. Use the tools.

    In the .net world, check out
    fxCop: http://msdn.microsoft.com/en-us/library/bb429476(vs.80).aspx
    StyleCop: http://code.msdn.microsoft.com/sourceanalysis

    These can both be used to prevent code building if it doesn't meet standards. Sadly, the first task for me is usually to turn on "warnings as errors" and get the code up to that minimal standard.

    Also check out Resharper: http://www.jetbrains.com/resharper/
    for flagging some code problems.

    The problem with code standards is that your best coders are probably using a standard already; and the while the worst can be dragged onto a standard, they will write bad code even with it.

    --

    My Karma: ran over your Dogma
    StrawberryFrog

  35. Re:Keep it simple! by LavaDog · · Score: 3, Funny

    I'm sorry, but that code goes against our coding standard by having non-const parameters and a goto. I suggest the following before submitting your changes:

    int multiply(int const a, int const b)
    {
      assert(a >= 0 );
      int x = 0, aNc = a;
      while (aNc--) x += b;
      return x;
    }

  36. Re:Keep it simple! by Anonymous Coward · · Score: 3, Funny

    -1, Dense

  37. Formatting vs coding practices by kevin_conaway · · Score: 2, Informative

    We found that it doesn't really help to enforce a *formatting* style on developers because everyone has their own. The only thing you really should be enforcing is tabs vs spaces (and it should be spaces) because mixing the two can produce some really ugly results.

    We have a much better rate of return running tools like JSLint or PMD to catch issues that are syntactically valid but will be sure to cause problems down the line

  38. Re:Keep it simple! by Anpheus · · Score: 4, Funny

    Try multiplying it by -1 and see if your stack is large enough.

  39. Language limitations vs common sense by DeKO · · Score: 2, Insightful

    I believe the worst standards are the ones that limit the languages to make them work as another language. Typically it's C++, or even Java, transformed into C. "No operator overloading, no virtual methods, no multiple inheritance, no function/method overloading, no const, no 'non-standard for' constructs, no return statements (other than at a function's end), no function call inside parenthesis (as an operator, or as an if/while test), no class constructors/destructors, no STL/Boost/whatever, no long (+15 chars) identifier names".

    Amazingly, even Google (which you would expect to only hire high-level developers) has some of these guidelines for C++.

    The best guideline is no guideline at all. Take your potential guideline, and present the rationale to the developers, with colorful examples to show what problems the guidelines are trying to avoid. Show them what "bad code" looks like and as soon as they realize they will naturally avoid it. If they argue against a specific rule it means that it's either a silly one (and should be discarded) or the guy is too dense to understand the problem (which means he needs more training, like maintaining a really awful code base).

  40. Languages, tools, and libraries by RAMMS+EIN · · Score: 2, Interesting

    In a way, the languages, tools, and libraries prescribed (if any), also constitute a sort of coding practice, in the sense that they impose limits on how you can structure your code.

      - The language you work with gives you certain language constructs. These constructs vary per language, and determine how you must express things and what abstractions are available to you. This has a huge impact on the structure of your code.

      - Most tools like to structure and format your code a certain way, particularly when the tool generates the code. This is usually a great boon, because it will make it easy for programmers to adhere to the same coding standard and hard for them to deviate. Of course, if what you want is not what the tool wants, the tool starts getting in the way.

      - The libraries you work with determine the APIs available to you. This also has a strong influence on the structure of your code. It also interacts with the language constructs available to you, as they may or may not make it easy to build an API you like to work with on top of the API that a library exposes.

    Abstraction is particularly important. If a language offers powerful enough abstractions, you can structure your program so that it is easy for humans to understand what it does, and have the compiler translate it to whatever the libraries make available to you. Better abstractions also make your code more reusable.

    As an example, in C, strings are character arrays. Arrays in C don't have a size associated with them. The end of a string is indicated by a character with value 0. Furthermore, the type of an array of characters is actually the same as a pointer to a character. C also doesn't have automatic memory management. Suppose now that you wanted to concatenate two strings. There are various ways to do so, but the most obvious one is the strcat function:

    char *strcat(char *dest, const char *src)

    This function appends src to dest and returns dest (a pointer to the concatenated string).

    That is, provided there was actually enough space in dest to hold the combined contents of dest and src, and the terminating NUL. If there wasn't, the function overwrites whatever came after dest, which will usually lead to your program crashing or executing code supplied by a cracker attacking your program.

    The correct way to use strcat, then, is something like:

    /* The first string, the second string, and a to-be-allocated string for their concatenation. */
    char *first, *second, *result;
     
    /* Don't forget to add 1 for the terminating NUL character. */
    result = (char*) malloc(strlen(first) + strlen(second) + 1);
     
    /* Copy the contents of first to result. */
    strcpy(result, first);
     
    /* Append the contents of second. */
    strcat(result, second);

    But wait! That's not all! Since the type of an array is actually a pointer, and pointers are allowed to be NULL in C, first and second in the above could actually be NULL. If either one of them is, the program will crash. So we need to add extra code to check for that ...

    All those many things to remember to concatenate two strings. It doesn't have to be that way. In OCaml, for example, a string is a string, not a pointer to a character, and never null. You don't have to worry about allocating a large enough block of memory, because memory will be allocated as needed, and reclaimed when no longer reachable. As it happens, OCaml also has an operator that concatenates strings. That is besides the point here, but I had to tell you that to explain what the code looks like in OCaml. Namely:

    first ^ second

    Not only is it much shorter than the C code, it's also easier to understand what it does, and more robust.

    I think this sort of thing matters a lot more than how you format or indent your code, and pretty much everything else that normally falls under the nomer of "coding standards".

    --
    Please correct me if I got my facts wrong.
  41. no multiple return statements? by dysfunct · · Score: 3, Informative

    maybe continue or multiple return statements were off-limits.

    Now why would anybody do this? I've always assumed code like this was basically what inexperienced people would use:

    if(condition) {
    // 100s of lines of code
    return true;
    }
    else
    return false;

    Why not just return immediately if any basic conditions or assumptions are not met and prevent that completely unnecessary indentation? The only advantage I can see is that you could miss the return statement when reading the code.

    --
    :/- spoon(_).
  42. Just read the classics for the best by vadmot · · Score: 2, Insightful
    Just read the classics for the best

    Linus Torvald Linux Kernel coding style http://lxr.linux.no/linux/Documentation/CodingStyle

    Bjarne Stroustrup C++ Style and Technique FAQ (Trivia and style section) http://www.research.att.com/~bs/bs_faq2.html

    The most of so called "Hungarian notations"(including the ones previously recommended by Microsoft) is the wrong interpretation of the original ones. No wonder that Torvald , Stroustrup, Sutter and Alexandrescu don't recommend them. However, the original notation are quit reasonable and can be found here http://msdn.microsoft.com/en-us/library/aa260976(VS.60).aspx

    Finally, there is the good book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices By Herb Sutter, Andrei Alexandrescu

    The best advice from this book " Don't sweat the small stuff. (Or: Know what not to standardize.)". For example " Don't specify how much to indent, but do indent to show structure" etc.

  43. Use a proper editor by DrYak · · Score: 2, Insightful

    Having to skim through thousands lines of html to find some embedded control statement.

    Or you could, you know, use an editor that does proper syntax highlighting (usually switches background color between HTML, Javascript or PHP) and has a proper search function.

    As a bonus, those editor are usually capable to reformat the code spacing and make it compliant with standard rules used in the code repository, so you'll have your "else" where *you* like it, and the editor will put it back in place for the others.

    --
    "Sufficiently advanced satire is indistinguishable from reality." - [Tips: 1DrYakQDKCQ6y52z6QbnkxHXAocMZJE61o ]
  44. Re:One of the worse: Iinterface by StrawberryFrog · · Score: 2, Informative

    This exposes an implementation detail to the user of the Object

    In many languages, an interface is not an object.

    and makes it difficult to refactor

    Refactor how, and how often do you do this? Reply under this comment, please.

    --

    My Karma: ran over your Dogma
    StrawberryFrog

  45. Dual widescreens by MarkusQ · · Score: 4, Funny

    You have dual widescreens? What's a dual widescreen?

    For one thing, they is grammatically plural.

    --MarkusQ

  46. Multiple exit issues - bogus problem by Animats · · Score: 2, Informative

    The prohibition on "multiple exits" or returns comes from a misunderstanding of early program proving technology. As one of the few people who ever built a real proof of correctness system, I know that's just not a problem.

    There are some topological restrictions on program proving, but you can't violate them with "break" or "return". You need "goto" to really screw up. The actual topological constraint is that backwards control paths must not cross.

    The basic requirement for proving loops is that there must be some section in the loop through which control must pass on every iteration. Somewhere in that section must go the loop invariant and the termination measure.

    Nobody does this for software any more, although, interestingly, full-scale machine proof of correctness of hardware logic in VHDL is not that unusual. There are commercial tools for that.

  47. Re:Dumb as coder by 4D6963 · · Score: 2, Funny

    Only bad coders/dumb asses write 20 lines of code for basic arithmetic.

    Only bad Slashdotters (if there can be any such thing)/dumb asses miss entirely such an obvious joke.

    I gotta say, nice code snippet though. I would have never thought of that one!

    --
    You just got troll'd!
  48. Re:Keep it simple! by 4D6963 · · Score: 3, Funny

    When you copy code you also copy whatever bugs exist in that code. If something needs to be reused several times then it should be made into a function.

    Crap, you're right! Fortunately there's an easy way to fix this :

    :%s/x+=b/x = addition(x, b)/

    --
    You just got troll'd!
  49. Re:Keep it simple! by 4D6963 · · Score: 3, Funny

    How about just x = a * b;

    How about just WHOOOOOOSH!!

    --
    You just got troll'd!
  50. Re:Keep it simple! by 4D6963 · · Score: 2, Funny

    Am I missing something, is the International Sarcasm Missing Day today??

    --
    You just got troll'd!
  51. Re:Keep it simple! by BlaisePascal · · Score: 3, Informative

    Even in languages that recurse properly that'll overflow on big numbers. To not overflow in properly recursing languages, you need:

    int multiply(int a, int b, int c = 0)
    {
        if (b == 0) return c;
        if (b < 0) return multiply(-a, -b, c);
        return multiply(a, b-1, c+a);
    }

  52. Re:Keep it simple! by Ibn+al-Hazardous · · Score: 2, Funny
    No, no, no! It's bad practice to use the post-decrement operator. The loop should read:

    do { x +=b; } while (--aNc);

    That way you won't create an extra copy of the variable when returning the value, it saves like an entire registry cell!!!1!

    --
    Yes, I am a biological organism. All rumors to the contrary are just that, rumors.
  53. The correct way to indent... by JeffAMcGee · · Score: 2, Funny

    Most people's ... programs should be indented six feet downward and covered with dirt.
    —Blair P. Houghton

    --
    This sig cannot be proven true.
  54. 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.

  55. Coding standards are stupid, better to localize by SuperKendall · · Score: 2, Insightful

    I don't see why anyone should have any coding standards at all.

    Think of it this way - there are a million code re-formatters that do a great job getting code into whatever form you like to see. So why not let someone work on code that is the most readable and ascetically pleasing to them?

    What really should happen is that operations to a source code control system all go through a filter that formats the code on the way in and out. Depositing source into a repository should format to a canonical standard that was acceptable - but anyone could re-format on checkout to whatever form they liked. Repository differences would work since the code would always have the same form. Diffs against you local changes could be presented against older code forms that were run first through your chosen filter so that diffs would appear in the form most pleasing to you.

    So all coding standards would be essentially local, except for the people who chose to work with the un-tweaked canonical format from the repository. An additional benefit was when it was time for layoffs, obviously anyone who cared about the code so little they did not seek to customize the view they have of it could be the first to go.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  56. Re:Keep it simple! by Anonymous+Brave+Guy · · Score: 2, Funny

    You'd better hope so. For loops and sparse data usually make a pretty inefficient combination...

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  57. log servers instead of printfs by heroine · · Score: 2, Insightful

    We're in an age of log server worship, where debugging is buffered & takes 50 macros to get working & as long as the program doesn't crash before the buffer is flushed, you get your trace, assuming you got all 50 macros set right.

  58. Re:Keep it simple! by caerwyn · · Score: 2, Informative

    Uh, no, not really. Especially when driven by specific profiling. I've gotten some pretty serious gains in tight loops on modern hardware with intelligent unrolling. If you've got stuff organized properly to stream out of memory and into the processor, you can get rid of pipeline stalls and significantly improve throughput for certain classes of loops.

    --
    The ringing of the division bell has begun... -PF
  59. if(ok && ).... by owlstead · · Score: 2, Interesting

    Let's not use exceptions but use a C++ integer named "ok" with an initial value of 1. Now write code like this:

    int ok = 1;
    if(ok)
        ok = MethodCall();
    if(ok)
        ok = expression; ...
    return ok;

    They argued it was easier to step over in the debugger and it saved you from checking code exits (code exits only allowed in the last statement).

    In Java Eclipse you can click the return value and all method exit point show up (including those for checked exceptions). For those Java programmers missing this brilliant feature.

  60. Whitespace is your friend by wmbetts · · Score: 3, Funny

    Personally I write stuff like
    if

    (

    a > b

    )

    {

    doSomething();

    }

    else

    {

    zomg();

    }

    Then I charge the client 5 * the number of lines in a all source and header files.

    --
    "Ubuntu" -- an African word, meaning "Slackware is too hard for me". - stolen from Dan C alt.os.linux.slackware