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

956 comments

  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 AndGodSed · · Score: 1

      Hey...

      That is actually quite true!

      thanks for the tip.

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

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

    6. 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
    7. Re:Some of those examples by thetoadwarrior · · Score: 1

      That is one thing I truly hate with a passion. The curly bracket belongs on the line with the if statement not below. Spacing can make things more readable but you can go too far with it.

    8. 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.
    9. Re:Some of those examples by Anonymous Coward · · Score: 0

      The latter is used quite often in GNU code. It is GNU coding style.

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

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

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

    13. 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.
    14. Re:Some of those examples by dosowski · · Score: 1

      If vertical space is an issue, why not do something like this?

      if(something_is_true) {
              do(something);
              do(one_more_thing); }
      else {
              do(something_else);
              do(one_last_thing); }

      The closing brace on its own line wastes just as much space as an opening brace would.

    15. 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.
    16. Re:Some of those examples by thegux · · Score: 1

      Personally I do:
      if (something)
      {
      statement;
      }
      else
      {
      statement;
      }

      I don't really understand why other styles seem to be more common myself.

    17. Re:Some of those examples by JebusIsLord · · Score: 1

      Example #1 is what the visual studio IDE wants you to use, and I've grown accustomed to it. Putting the opening brace on the same line as the control statement (K&R styple) SEEMS to make more intuitive sense, but in practice I find example #1 a lot easier on the eyes.

      --
      Jeremy
    18. Re:Some of those examples by ilovegeorgebush · · Score: 1

      Each to their own. It gets lost by people who scan read too much.

      Swings 'n' roundabouts.

    19. 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
    20. Re:Some of those examples by TheLink · · Score: 1

      What's so readable about having to scroll more to read code written that way? The indentation should identify the blocks already.

      IMO it doesn't add any more useful information that a more compact indentation style does. I prefer it more compact vertically while preserving code block indentation (don't want those perl "one liners" that are 20 code lines in one line). If I ever want the lines to be further apart vertically I can always push my nose closer to the screen, doh.

      When you start adding comments you see even less of the code on one screen.

      I'd rather be able to stare at more code on the screen and let my brain figure it out. A decent editor/IDE will let you identify matching braces and blocks of code.

      Of course if you get paid by lines of code things might be different... ;)

      --
    21. Re:Some of those examples by marcosdumay · · Score: 1

      I have a problem with the '}}' at the end. It is very easy to lose one of the braces.

      I can understand why people use it with Lisp, parenthesis are easier to read (or I'm more used to them, I don't know). Also, Lisp has shorter routines than C-derived languages.

    22. Re:Some of those examples by kv9 · · Score: 2, Funny

      one true brace to rule them all, heathen!

    23. Re:Some of those examples by marcosdumay · · Score: 1

      Of course, if your entire team uses an editor that will correctly ident the lines, like emacs or vi, putting the braces on single lines isn't necessary. If someone just insterts a line there, they will make it clear that the line isn't on the loop.

      Now, why lots of IDEs insist on requiring TAB and BKSPACE clicks is a mistery to me.

    24. Re:Some of those examples by dosowski · · Score: 1

      I prefer vertically aligning open and close braces, too. I was just making a point that the people who do the same-line open brace and use the vertical-space argument are only getting it half right. If the one line from the open brace is that important, they should also be doing something about the wasted line from the close brace.

      If you aren't going to line up the braces, get them out of the way and just use indentation for visual identification of blocks. If you are going to use one brace for a visual aid, use both of them and make them at least look like they are associated with each other (by aligning them vertically).

      In my example, I get rid of the idea of pretending to use one brace for a visual aid and instead use only indentation. Some say the beginning of a block can be seen by the increased indentation. Can the end of a block not also be seen by the decreased indentation as you back out a level? The braces are there only because the syntax requires them. They are out of the way because they aren't being used for any human-readability.

      Having said all that, I still prefer keeping the braces out there where I can see them.

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

    26. Re:Some of those examples by jgoemat · · Score: 1

      One thing I like best is placing the open brackets on their own line, as well as using them even if there is only a single statement in the block.

      if (contition)
      {
        DoSomething();
        for (int i = 0; i < 100; i++)
        {
          DoSomethingSeveralTimes();
        }
      }
      else
      {
        DoSomethingElse();
      }

      I like knowing that there will always be a block when there can be and I can add and remove code, such as a print for debugging, without worrying about adding or removing the braces to maintain functionality or coding practices.

    27. Re:Some of those examples by Jeremi · · Score: 1

      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.

      I have to agree with this.... there are many more or less acceptable programming styles out there, and a reasonably experienced programmer can grok most of them with a few minutes of effort. What really counts is what the code does and how the code does it, not so much whether the curly braces are in one spot or another.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    28. Re:Some of those examples by kramulous · · Score: 3, Insightful
      I don't know where I picked it up (Java ??!) but I pretty much always use:

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

      I find that tracing parenthesis is a lot easier.

      --
      .
    29. Re:Some of those examples by 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/
    30. 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

    31. Re:Some of those examples by Anonymous Coward · · Score: 0

      it's a huge waste of vertical space and you don't gain much readability.

    32. Re:Some of those examples by cryptoluddite · · Score: 1

      I prefer vertically aligning open and close braces, too. I was just making a point that the people who do the same-line open brace and use the vertical-space argument are only getting it half right. If the one line from the open brace is that important, they should also be doing something about the wasted line from the close brace.

      But you must know that your argument is retarded, right? You are saying that if something is good then twice as much is better. Let alone that being a false argument, but the opening brace and the closing brace aren't even equivalent in the first place.

      Putting the opening brace on the same line has few if any drawbacks, but putting the closing brace on the last line has drawbacks, such as the inability to add a later statement without moving the brace between lines, adding a properly scoped // NOT REACHED comment, or other things people do.

      The fact that you would propose such a ridiculous argument tells me that you know that opening braces on their own line is at best a style choice with drawbacks, and that you are defensive about it and need to rationalize it. In other words, you know K&R is a more efficient style yet you would rather tear it down with false arguments than adopt it... what does that say about you as a programmer?

    33. Re:Some of those examples by pigwin32 · · Score: 1

      I truly disagree with you. Having spent the best part of a year coding in Java and using the Java style with the open brace on the same line the best I can say is that I have gotten used to it. Code Complete has a section on indentation that recommends the Java/K&R style and it is one of the few sections I fundamentally disagree with. Later in the text there is a recommendation to comment closing braces with e.g. // end while (or similar) which to me highlights the problem. If opening and closing braces are vertically aligned with the controlling statement it is obvious which section of code the brace is closing (unless the code section is so long that the opening and closing braces aren't both visible in the code window but no-one codes like that any more right?).

      I much prefer Allman style, and a little extra vertical spacing just helps code clarity - the days of needing to make the most of screen real-estate went out with the 80x24 green screens.

    34. Re:Some of those examples by Anonymous Coward · · Score: 0

      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.

      As other replies pointed out, its the format "standard" used in existing code or projects. Its always best to keep it consistent across all pieces of the project to keep from adding to the headache of already trying to decipher someone elses code.

      Aside from that, I generally append the opening curly to the conditional requiring it, and leave the closing curly on its own line with the else or elsif starting another line with its opening curly on that line as well. ie:

      if( $blah =~ /foo/ ){
      $bleh = 'bar';
      }
      else{
      $blah = 'foobar';
      }

      To me it makes more sense, in that the curly is "attached" to what opened it. In Perl, at least, a block can exist as an anonymous block when not preceded by a conditional or loop. By sticking the curly on the same line, you know what started it, and thus that it is not just an anonymous block (useful to break from a series of commands outside of an if statement, amongst other things). The closing curly being on its own line keeps the block separate from anything else, so its easier to find and easier to update if you are changing the conditionals involved (ie: adding an elsif before the last else, adding a continue statement to a loop, etc). Besides that, it helps the auto-indent and bracket chasing/checking functions of editors work better (works great in Jed).

      tm

    35. Re:Some of those examples by tdelaney · · Score: 1

      I've always used (and prefer):

      if (condition)
      {
          true_branch
      }
      else
      {
          false_branch
      }

      (even on a 512x384 original Mac screen) but have no significant complaints with:

      if (condition) {
          true_branch
      }
      else {
          false_branch
      }

      I find the first easier to read even though as a python programmer I find that for multiple statements in a branch, the following (which matches the above) is easiest to read:

      if condition:
          true_branch_statement
          true_branch_statement
          true_branch_statement
       
      else:
          false_branch_statement
          false_branch_statement

      If there's only a single statement I prefer to put the else: hard against the true_branch:

      if condition:
          true_branch
      else:
          false_branch

      I hate the GNU style with a passion:

      if (condition)
        {
          true_branch
        }
      else
        {
          false_branch
        }

      Any brace style that puts the brace on the same line as any statement of either branch is just asking for trouble - way too easy to select a line and delete or move it, and in the process totally messing up the logic.

    36. Re:Some of those examples by Kjella · · Score: 1

      I guess that depends on your intentation style. If brace == intent, it's very clear since it's:

      if () {
      ....// CODE
      } else {
      ....// CODE
      }

      If you're not intenting, I don't think anything can help the else from getting lost...

      --
      Live today, because you never know what tomorrow brings
    37. Re:Some of those examples by YourExperiment · · Score: 2, Insightful

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

    38. 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)
    39. 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.
    40. 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)
    41. Re:Some of those examples by Anonymous Coward · · Score: 0

      We've found that the else statement gets more lost when it's on a seperate line. The problem is that in simple examples, it looks cleaner this way:

      if (condition) {

      }
      else {

      }

      But in real code it becomes harder to see where the condition ends. Using the 'else on same line as the closing bracket' style, the entirety of the if statement completed when there was a solitary closing brace at the same indentation level.

      We had the problem that if someone wanted to add some comments to the else, then we get this:

      if (condition) {

      }

      //here are some comments about else
      else {

      }

      Causing the 'else' to get lost.

    42. Re:Some of those examples by MichaelSmith · · Score: 1

      Density is the opposite of readable and maintainable.

      So you would agree with a code reviewer who insisted I insert one blank line between every two lines of code?

    43. Re:Some of those examples by kramulous · · Score: 1

      If the one line from the open brace is that important, they should also be doing something about the wasted line from the close brace.

      What? Being consistent? No, no, no ... we can't have that!

      --
      .
    44. Re:Some of those examples by kramulous · · Score: 1

      I can certainly understand that the "else" would get lost, but I'd put the comment for the "else" just inside the opening brace on the next available line.

      If the "if" statement has an associated "else", the "else" will always be on the next line after the closing brace of the "if".

      Just my $0.02

      --
      .
    45. Re:Some of those examples by freakxx · · Score: 1

      I am not a professional in coding but I always found the following more readable and easy to understand:

      if(condition)
              {
                statement1;
              }

      else{
                statement2;
              }

      In case of multiple and nested if-else situations, I found it very easy to follow.

    46. Re:Some of those examples by TENTH+SHOW+JAM · · Score: 1

      I for one am opposed to overtabbing. I write a lot of scripting that may need editing in situ with a cheap and nasty text editor (notepad). The default number of spaces in a tab is therefore 8. If we use your last example we find that we are going 16 spaces deep to look at "stuff". Now if we have a couple of loops and some more if in, this can get to 64 deep before we get to "buriedStuff". If you use the first convention, this is reduced to 32 deep.


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

      is my personal preference since I read this as "If something is something else then, do stuff. Else [then] do otherstuff." I tend to associate open curlies as "then do" tabs as commas and closing curlies as fullstops.

      --
      A sig is placed here
      To display how futile
      English Haiku is
    47. Re:Some of those examples by godglike · · Score: 1

      I've always used your first option and the only reason I know of not to use it is that C programmers find it reminiscent of Pascal.

      if (test)
      begin
          operation
      else
          other
      end

      or something, it's been a long time since Pascal for me.

      The doubly emphasised if and else is really useful.

      BTW Just had a look at K&R and they use trailing bracket for loops and if but lowered bracket for functions. So they were a little confused too.

    48. Re:Some of those examples by severoon · · Score: 1

      I think we can all agree that it doesn't make a whole lot of difference how one formats if-else blocks...however, I will say this much about it: if you consider knocking out sections using comments, then this style makes the most sense:

      if( test ) {
      // blah blah blah
      }
      else {
      // blah blah blah
      }

      This way, you can just grab the else lines and line comment them out in your IDE very quickly without leaving dangling braces, so the commented version will compile and you can test it quickly before reverting the commented block. On the other hand, if you put opening braces on a separate line, and accidentally comment out the "if" or the "else" statement, in many languages the braces just become a valid scope and the code compiles and executes. But that's probably not what you intended, so it would be much better if the IDE would let you know.

      --
      but have you considered the following argument: shut up.
    49. Re:Some of those examples by Ninja+Programmer · · Score: 1

      Mod parent up.

      I don't even understand the argument for putting parentheses on their own line. It cannot be more readable except where its trading off screen space. With proper indenting, visually recognizing:

            }
            else
            {

      and

            } else {

      takes the same mental training and effort. The first just wastes additional LCD elements. As I explained to a former boss, I will use the "brace on its own line" coding convention if he buys me a 50" display upon which to read my code.

      Readability has to be metered against "content per line read". The maintainability of code has nothing to do with how easily its read. It matters how much content can be understood with the same effort. Brace on its own line is a total loser on the measure.

    50. 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.
    51. Re:Some of those examples by severoon · · Score: 1

      Actually, a much bigger problem that I see is the random creation and placement of temporary variables. Code like:

      int foo = someObject.getCount();
      // ... 100 lines of code ...
      logger.log( "foo: " + foo ); // only use of foo

      Why not just call someObject.getCount() when it's needed instead of storing it way at the top of the method?

      Or worse, people will create a single method-local variable far away from its first use, and then periodically store new objects in the reference, each of which is used once.

      Don't get me wrong, there are times when storing intermediate results in method-local vars is necessary, either from efficiency or design standpoints, but far too much do I see other people I work with create 15 temp vars and use each one once at random places. This is why, in Java, I've started using the final keywork with abandon. In the cases where I can't avoid creating a method-local var, I make it final. If you're reading my code and you see a non-final method-local var, sirens go off and you realize something is up.

      --
      but have you considered the following argument: shut up.
    52. 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?

    53. Re:Some of those examples by enoz · · Score: 1, Insightful

      A common mistake I have seen programmers make is removing a branch from an if-else statement.

      if {

      } else {

      }

      With the above format it is very easy to accidentally remove the brace preceeding the "else" when removing the else branch.

      if {

      }
      else {

      }

      With this coding style it is less prone to disastrous pruning.

    54. Re:Some of those examples by jc42 · · Score: 1

      A friend just showed me the programming style guidelines that had been handed down to his development group from on high. It included the common "terminal braces on a separate line" rule.

      The fun part was that his group is doing almost all their work in python.

      He wondered how long it'll be before his group is criticised for blatantly violating this style rule? (If he tells me, maybe I'll report it here. ;-)

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    55. Re:Some of those examples by CecilPL · · Score: 1

      if (someCondition) { doStuff(); } else { dont(); } Has always seemed the most readable and maintainable style for me. Everything is well-spaced and reads easily. The braces line up vertically for easy matching. And honestly, if you have huge functions that take up more than two vertical screens you should be splitting it up anyway. Not to mention, one (admittedly minor) benefit I rarely see mentioned is the ease of making if-blocks unconditional. It's simply a matter of commenting out the if-line and leaving the braces in place.

    56. Re:Some of those examples by CecilPL · · Score: 1

      err, that would be:

      if (someCondition)
      {
          doStuff();
      }
      else
      {
          dont();
      }

      Sorry, I'm new at this.

    57. Re:Some of those examples by jc42 · · Score: 1

      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've worked on a few projects where we were provided with a batch of formatting programs. There was an official "archive" style, and a formatter that converted any code to that style. But every programmer could easily convert code to their preferred style.

      This made the management happy, because all the archived code was in the official style. Also, when management decided to change the official style (which sometimes happens every few months if managers have too much time on their hands), it's fairly easy to write a script to reformat everything in the archives. And it prevents programmers from wasting their time dealing with the usual criticism from a manager that they didn't format one line correctly in some bug fix.

      The only real problem is that sometimes the "pretty print" formatters will make changes that affect the meaning of the code. This is pretty obvious with languages like python, where line terminators have syntactic significance. I've also seen it happen in C, where a formatter doesn't quite handle the fact that line terminators are significant in lines that start with '#'.

      There's also a generic problem that a lot of us like to put comments to the right of code, and most formatters destroy the alignment of such comments. Of course, this doesn't much bother the programmers who never read the comments.

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    58. Re:Some of those examples by __aahgmr7717 · · Score: 1

      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.

      IF condition THEN
      ELSE
      END

      #define IF if(
      #define THEN ){
      #define ELSE ;}else{
      #define END ;}

      Since I was raised on Algol I find the
      "IF THEN ELSE END" construct far easier to see and read.

    59. Re:Some of those examples by Anonymous Coward · · Score: 0

      Why not:
      if
        (
           something
        )
        {
           stuff
        }
      else
        {
           other stuff
        }

    60. Re:Some of those examples by Anonymous Coward · · Score: 0

      When everything is blessed with brackets:

            if (foo == bar) {
                      shout = 1;
            }

      I see the "if" and I can match it up with the closing brace - you
      don't really need to see that open brace.

      Blessing everything with braces was one of the more important coding
      practices of one of my employers.

      putting the function name starting in the first column was another

      long
      foobar()
      { ...
      }

      so one could do a search for ^foobar and find the function, and not the invocations.

    61. Re:Some of those examples by cryptoluddite · · Score: 1

      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.

      K&R style has more pro- points in its favor and fewer con-s than any of BSD, MS, or GNU styles. If you 'grok' a style better that is objectively less efficient and that makes you more efficient then so be it. To each his own.

      But don't make up bogus arguments to justify that.

    62. Re:Some of those examples by jc42 · · Score: 1

      Of course if you get paid by lines of code things might be different... ;)

      I think you've hit onto something there. After all, counting lines of code is obviously silly. Do you really think it's a Good Thing if programmers are rewarded for increasing their line count? I can always make any piece of code take more lines. Nonetheless, nearly everything you can find about the "size" of software uses lines of code as the unit.

      So it's not surprising that programmers (and their employers) would find excuses for increasing the line count. Putting braces on separate lines is a very easy way of increasing your line count without adding any value whatsoever to the code. Blank lines are even easier, at one keystroke per. Programmers are rewarded for doing this, so of course most of them will advocate it.

      My other theory has been that the manufacturers of computer displays are also behind the "maximize line count" programming styles. A programmer can really only work with the code that can be fit onto the screen. If you encourage space-wasting coding styles, then obviously the programmers are going to need larger screens. If you can sucker programmers' employers into enforcing every-brace-on-a-separate-line styles, you have successfully sold them larger, more expensive displays.

      I've long known that I can work fastest with compact coding styles. The reason is trivial: The more code I can fit onto the screen, the less wasted time I have scrolling around. Of course, I also need several windows for the output of test runs, and I'm most productive if those windows are as large as possible. And I always want the largest (most pixels) display I can get.

      But it's been very clear to me on any number of projects that the managers aren't really concerned with maximizing my speed and efficiency. If they were, they'd never approve the sparse coding styles that they always seem to prefer.

      (Actually, what I'm looking for is some valid time-and-motion studies of such things. All we're reading here is really untested BS, really. The few so-called studies have either had samples sizes so small as to be meaningless, or they don't even bother mentioning the sample sizes. Where's the data with error bars and levels of significance that will persuade me that people are doing anything other than pushing personal artistic preferences? ;-)

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    63. 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.

    64. Re:Some of those examples by randallman · · Score: 1

      # Please !
      # All those braces give me a headache.

      if something:
          stuff()
      else:
          other stuff

    65. Re:Some of those examples by dosowski · · Score: 1

      But you must know that your argument is retarded, right?

      Even with you starting out with a comment like that, I'll try to take you seriously...

      You are saying that if something is good then twice as much is better.

      No, that's not what I'm saying. Perhaps that's how your interpreted it, but I'm not saying "more, more, more!" (I'm actually more of the opinion that that one or two lines shouldn't really be such a big issue). I'm just suggesting that it looks like a lack of consistency between the use of the open brace and the close brace. I'm also saying that if that one small line is so important, then that other basically wasted line should be a consideration for those people as well, unless there is a good reason for it to have its own line (see below).

      Let alone that being a false argument,

      What makes it a false argument? Pointing out that people aren't following their own reasoning is a false argument? Ok...

        but the opening brace and the closing brace aren't even equivalent in the first place.

      Putting the opening brace on the same line has few if any drawbacks,

      It does have at least one drawback: readability. That's why some people prefer to put it on its own line. If you disagree about the readability thing, fine, but some do see it as a drawback to putting the open brace on the end of the previous line.

      but putting the closing brace on the last line has drawbacks, such as the inability to add a later statement without moving the brace between lines, adding a properly scoped // NOT REACHED comment, or other things people do.

      This is a good point. Of course, adding a line and moving the brace is not that difficult, but it is some extra effort that is avoided by putting the close brace on its own line. If that outweighs the vertical spacing issue, I'll accept that.

      The fact that you would propose such a ridiculous argument tells me that you know that opening braces on their own line is at best a style choice with drawbacks,

      Well of course, ALL styles have drawbacks and advantages, and different people have different priorities about those advantages and disadvantages.

      and that you are defensive about it and need to rationalize it. In other words, you know K&R is a more efficient style yet you would rather tear it down with false arguments than adopt it...

      No, you completely misunderstood me. I was absolutely not defensive about it or trying to rationalize it. In fact, I tried to say very little about which style is better. If you say K&R is more efficient, I was suggesting a way to make it even more efficient, or whatever.

      Here's a way to look at what I was saying: For purposes of this discussion, say there are two styles: A and B. Some prefer A, some prefer B. I use A, you use B. I will continue to use A for whatever reasons I choose, but if you choose to use B, here is a suggestion on how you might optimize your use of style B, using the very reasoning that leads you to use B in the first place.

      what does that say about you as a programmer?

      Ok, I apologize for taking this quote out of context, but what it says about me is that I try to be helpful. Perhaps you thought I was being sarcastic or something. I wasn't saying your style is worse because of some slippery-slope argument. I actually recognize that people have their preferences for whatever reasons they have. I was genuinely offering a suggestion on how to improve a coding style I don't use just because I didn't understand the inconsistency in the style. You did point out a problem with my suggestion, but as I said before, all styles have advantages and disadvantages. It's up to you to decide which ones are important to you.

    66. Re:Some of those examples by xjimhb · · Score: 1

      Sorry, that's not correct Pascal. Try:

      if condition then
          begin
              stuff
          end
      else
          begin
              otherstuff
          end

      That may be the reason I like GNU-style for C since I have done a LOT of Pascal programming in the past. Frankly, I prefer it to C, but everything is in C or C-ish languages nowadays, so its not worth flagellating that moribund equine any longer.

      And the other thing people seem to be complaining about is the size of tabs ... well, I ***HATE*** tabs, I don't use them, and my indents go in units of 2 SPACES (spacebar spaces). DOWN WITH TABS!!!

    67. Re:Some of those examples by fj3k · · Score: 1

      I find it a hell of a lot easier to find the matching braces when they are all on their own line. If you've got a large set of long lines, you don't have to always scan back to the start of the lines to see where the block starts and ends, you can see the almost empty line that shows where it starts and ends while you're scrolled far to the right. I was so glad when I started work and found that was the standard they used.

      --
      Two men claimed to have walked into a bar. Only one had the bruises to prove it.
    68. Re:Some of those examples by KutuluWare · · Score: 1

      I can't give you a good reason it's not used. I can give you the realistic reason: because most programmers have some deep-rooted visceral hatred of white space no matter how much more readable it makes your code. (At least I haven't seen anyone on /. make the argument that it makes your source files "too big", which is one I deal with at work from fresh-from-college juniors all the time.)

      Seriously -- when you were writing on a 24 line terminal in a line editor, yeah, maybe minimizing blank lines was important. My IDE displays 50+ lines of code at a time, with collapseable regions. If any single logical block of code is so long that I have to scroll excessively to follow it, I likely have much bigger problems than just lots of braces.

    69. Re:Some of those examples by Mean+Variance · · Score: 1

      So it's not surprising that programmers (and their employers) would find excuses for increasing the line count. Putting braces on separate lines is a very easy way of increasing your line count

      While I agree in the general sense about the (lack of) value of KLOC - 1000's Lines Of Code - counting for "defect density metrics," if they are there, at least some semi-intelligent program should be doing the line counting rather than a gross wc -l. The basic variants should be the same line count.

      I, and probably every developer I've ever talked to, agrees about the dubious value of line counting. From my experience, even the managers hate it. They're stuck in the middle because they have to report a "SMART" metric up the chain of command.

      To me, the only value of line counts is for historical perspective over the period of years of releases just in the same way you might want to see the growth of how many classes you've created for 5 years of annual releases. Even then, I see the value not much beyond curiousity and nothing else.

      On the subject of coding style, our developers use the opening brace (Allman?) on its own line style. We're a Java shop, but the original developers were from the Visual C days where that was more common. I like it because I'm used to it. In the end, my hangups are built upon consistency and nothing else.

      If the architects want to change to K&R or something else next release, fine - do it, just as long as everyone complies. Rogue developers can be a real PITA when it comes to this.

    70. Re:Some of those examples by cryptoluddite · · Score: 1

      I'm just suggesting that it looks like a lack of consistency between the use of the open brace and the close brace.

      It is an inconsistency. Often something that is most practical or efficient is somewhat inconsistent.

      I'm also saying that if that one small line is so important, then that other basically wasted line should be a consideration for those people as well, unless there is a good reason for it to have its own line (see below).

      And I've seen code where ~20% of the lines are open braces. That's hardly "one small line". Again, "one small line" is dismissive and is a bogus argument.

      For purposes of this discussion, say there are two styles: A and B. Some prefer A, some prefer B. I use A, you use B. I will continue to use A for whatever reasons I choose, but if you choose to use B, here is a suggestion on how you might optimize your use of style B, using the very reasoning that leads you to use B in the first place.

      Hardly. More like, if people prefer B they are "only half right" and should be using style C instead. And C is a defective style since it (obviously) impedes editing. Therefor A is a better style than B.

      You can see how that is a bogus argument right?

    71. Re:Some of those examples by Anonymous Coward · · Score: 0

      I'm sorry you have a problem with "Density Factor". Perhaps additional remedial classes and/or therapy may help you overcome your "Density Factor". But probably not. Try a vocational school, and stop pretending...

    72. Re:Some of those examples by thestigg · · Score: 1

      Because the industry is filled with some old grumpy types who would rather see hell freeze over than let us code in this very sensible manner. I agree with you... this is hands down the most readable method.

    73. Re:Some of those examples by mathew7 · · Score: 1

      I don't try to be negativist, but you WILL get lost is someone does not respect the else branch ident with it's coresponding if in case you have many if/else conditions. One ident is wrong, and who knows what you read. I'm always for open-after-statement and close on ident, with only "else" being accepted after a closing. A brace opening on new line seems to take too much vertical space, especially since the desired transition of the manufacturers to widescreens.

    74. Re:Some of those examples by randyleepublic · · Score: 0
      Why not this:

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

      }

      ? I like to see the braces in line so that I can easily parse the pairs as being complete. Also by not having the line feeds after the braces, the code is not overly vertical.

      --
      Social Credit would solve everything...
    75. 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.
    76. Re:Some of those examples by Fourier404 · · Score: 1

      Better than putting every two lines on the same line.

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

    78. Re:Some of those examples by N+Monkey · · Score: 1

      But, IMHO, it did make a very good example. :)

    79. Re:Some of those examples by Anonymous Coward · · Score: 0

      You realize that you're putting words in his mouth right? I haven't written much code (I'm 17), so I came here with a relatively open mind, but now that I see how much of a dick people who write in your style are, I think I'm gonna stick with whatever the other guy uses. Hopefully it'll land me a job where I don't have to talk to you. If you think I'm making a faulty argument, you should reread your own posts.

    80. Re:Some of those examples by DaveDerrick · · Score: 1

      I agree with you on this, its MUCH more readable like this. Some ppl are saying is more effort to write, but remember that code written by you gets read by others & vice versa. Making the code easily readable is #1 priority IMHO, and this is how to do it.

    81. Re:Some of those examples by RotHorseKid · · Score: 1

      Not exactly.

      Dense is the opposite of maintainable and readable.
      Density, however, is the opposite of maintainability and readability.

      But I guess you meant exactly that.

      --
      Nobody writes jokes in base 13. - DNA
    82. Re:Some of those examples by dkf · · Score: 1

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

      The only reason I can think of for not packing "else" tightly is when you're using an editor without syntax highlighting. But since I don't write code in Notepad.exe or classic /bin/vi, I don't care. Use your tools, folks!

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    83. 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
    84. Re:Some of those examples by Jesus_666 · · Score: 1

      But don't make up bogus arguments to justify that.

      Such as? The advantages of the Allman style I enumerated were explicitly stated as applying to me. Of course you can claim to know better than me how my brain works but that would be rather far-fetched, as would be claiming that all code blocks are always indented sensibly all the time everywhere.

      It might be that 1TBS has more advantages if you consider a completely average coder but my very point is that not everyone is average and thus not all advantages/disadvantages apply for everyone.

      --
      USE HOT GRITS WITH STATUE OF NATALIE PORTMAN (NAKED AND PETRIFIED)
    85. Re:Some of those examples by Kent+Recal · · Score: 1

      As a python programmer I find this discussion refreshingly amusing! ;-)

    86. Re:Some of those examples by Anonymous Coward · · Score: 0

      Oddly enough, I find that the else is lost in the first case. It's no longer attached to the if, it's hanging out there like it's its own separate logic structure. Cuddling the else chains it into the logical structure it belongs to.

    87. Re:Some of those examples by Ian-K · · Score: 1

      For my tastes this is horrible: It's brackets galore. In any fairly complex piece of code you'll need to scroll all over the place and it's way too much formatting sugar. Seems to me like the people who prefer this style have a problem tracking logic sequences.

      Ok, so maybe I overdid it a bit in the previous paragraph. But my point is: it's all subjective. You like it this way, lots of others (apparently) like it another way.

      While on the topic... one coding practice that I was taught while working for a large company was:

      "Keep your methods shorter than 10 lines".

      Actually makes the code a lot more readable (but you have to be careful so as to break up your code in such a way that you don't get performance hits from the increased function calls (stack).

      --
      I'm no longer fed up with MS Windows: I go rid of them :)
    88. Re:Some of those examples by tonytraductor · · Score: 1

      Maybe it's just me, but, in tcl, as well, I find it best to
      } else {
      I don't understand at all why otherwise the else gets ignored sometimes.

    89. Re:Some of those examples by ThirdPrize · · Score: 1

      Say what you like about VB but you knew where you were (literally) with End If, End Sub and End Select, etc.

      --
      I have excellent Karma and I am not afraid to Troll it.
    90. Re:Some of those examples by dosowski · · Score: 1

      Hardly. More like, if people prefer B they are "only half right" and should be using style C instead. And C is a defective style since it (obviously) impedes editing. Therefor A is a better style than B.

      Actually, I would replace that last line with "If you don't like the editing issue of C, then go ahead and stick with B. I don't care." I was never trying to say that A is better than B. You don't seem to understand that.

      You keep talking about bogus, false and "retarded" arguments as if I'm trying to debate against your opinion. You seem to miss the point entirely.

    91. Re:Some of those examples by Nurgled · · Score: 1

      Despite all of the arguments for the different styles, really in most cases it just comes down to what you learnt first. The projects I started with used the opening-braces-on-the-same-line style, so that's the style I'm most comfortable with.

      If you pressed me to justify it, I'd probably respond that I only add newlines before or after bracketing delimeters, which means that you can just scan down the right of all lines to see whether they introduce a block or list ({, (), end a statement (;, }) or end an item in a list (,). This falls down in languages that don't let you end the terminal item in a list with its own comma, of course.

      Really though, you could easily make a counter-argument that'd be just as valid. ("The lack of any symbol indicates the start of a block", for example.) It's just a matter of what you're used to.

    92. Re:Some of those examples by hesaigo999ca · · Score: 1

      I tend to agree, I develop in C# and have to declare objects with the new etc..
      sometimes my lines can be a bit long, but i still keep them all on the same line, why....
      cuz' when i create a function that does xyz you can actually fit the functions lines in the screen size, and not have to scroll 3 pages down to see the rest, I imagine some have the same idea about all on the same line, scrolling towards the left, but to change lines for a few "" & "" & "" is ridiculous....

      But then again this is what is means to be human, and different.

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

    94. Re:Some of those examples by God+of+Lemmings · · Score: 1

      Its because of this.

      #Some comments go here.
      if (foo) {

            do_something();
      } # maybe here.

      # more comments go here.
      else {

            do_something_else();

      }# maybe here

      --
      Non sequitur: Your facts are uncoordinated.
    95. Re:Some of those examples by DaFallus · · Score: 1

      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
      }

      I'm certainly not the best or most formal programmer in the world, but this is the way I prefer. It helps me visually line up any opening and closing brackets for a statement. Having to count through a mangled tree of brackets just wastes my time. I'm sure other people can quickly read through the logic and cram the entire statement on one line; I just find that this is what works best for me.

      --
      No one cares what your captcha was

      Houston TX, USA
    96. Re:Some of those examples by Anonymous Coward · · Score: 0

      Go and reread the other posts while you're at it. Some people are "only doing it half right" and should do it some other way. Yes, I have been disrespectful. But I haven't put words in the guy's mouth.

    97. Re:Some of those examples by Zenaku · · Score: 1

      I agree with you about how this sort of thing isn't worth thinking about, but I think that it is the desire to have the code consistent rather than one way or the other that *leads* to people arguing about it in the first place. I think most developers would agree that things like this are small potatoes, but once somebody makes an issue of it, everybody is on one side or the other. It's just like that war in Gulliver's Travels between Liliput and Blefuscu, over which end of an egg should be opened first.

      For example, I don't really care much if someone puts their braces on a separate line or not. I can read it easily either way. That being said, I do it one particular way, because that's the way I'm comfortable with and in the habit of. Once someone comes along and says "We're going to have a standard for this," I will fight tooth and nail to make sure MY way is the standard, because otherwise I will be constantly having to remember to do it a different way, or constantly reformatting my code. It slows me down and keeps me from getting into a good groove if I'm always stopping to "correct" my formatting.

      I say things like this are so trivial, that I don't need them to be consistent. Let each developer do it however he or she likes -- it won't bother me if they do it differently than I do. Being forced to do it in a way that is unnatural for me does bother me.

      And eggs should be opened on the wide end, dammit!

      --
      If fate makes you a motorcycle, you become a motorcycle.
    98. Re:Some of those examples by jc42 · · Score: 1

      If the architects want to change to K&R or something else next release, fine - do it, just as long as everyone complies. Rogue developers can be a real PITA when it comes to this.

      Well, I'd say that's not the right approach. If management wants coding style Foo, they shouldn't waste programmer time with it. It's a job for the computer. Just make the checkin command run the code through a formatter that converts to style Foo. And, to keep your "rogue" programmers happy, include the usual formatters that can convert to their favorite styles. That way, the programmers can get a compact, efficient style if they want it, while others can see the styles that they like.

      But trying to get programmers to agree on a style is just a waste of everyone's time. That's the sort of jobs that's much better done by a computer. Then your programmers can spend their time doing something productive, rather than throwing away their time on dumb formatting tasks.

      There's no shortage of code-formatting programs. And many of them are open source, so if your official style is unusual, you can add add its features to your formatters.

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    99. Re:Some of those examples by SQLGuru · · Score: 1

      Hear! Hear! The number one coding standard should be consistency. It is better to be consistent and wrong than to be inconsistent.

      Layne

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

    101. Re:Some of those examples by iwein · · Score: 1
      Thank you.

      Coding standards may have a formatting template with them. I will press ctrl-shift-F before checking in my code and get used to whatever template you give me. Being anal about formatting is a sign of being a bad developer. Nesting if statements to a point where this is going to have impact is a sign of being a moron.

      --
      Show a man some news, distract him for an hour. Show a man some mod points, distract him for the rest of his life.
    102. Re:Some of those examples by Eccles · · Score: 1

      The curly bracket belongs on the line with the if statement not below.

      But then it gets lost if the if condition (or for loop specifier or whatever) is long. You can tell from a distance if code is properly formatted if it has curly brackets on their own line, the same is not true of curlies at the end of a line.

      I'd also like to see color (and/or font) used to help identify matching parentheses. Also, a warning if indentation does not match the bracketing would be useful.

      --
      Ooh, a sarcasm detector. Oh, that's a real useful invention.
    103. Re:Some of those examples by Anonymous Coward · · Score: 0

      As a PHP guy, I personally love using the alternative syntax:

      if(condition):
      else:
      endif;


      no curlies, no debate :P

    104. Re:Some of those examples by somersault · · Score: 1

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

      Likewise. It may take up more space, but it makes everything look neater and structured.

      I just realised while thinking about this in that it's the same kind of thing I do when I take a photo - I like to have a clearly identifiable subject with some 'white space' to frame it, rather than an incoherent mass that has been clipped in a strange place. Even if framing in such a way isn't directly possible, I still try to make the cutoff as logical as possible, without any distractions.

      If for example the conditions in an if statement are quite complicated, I will split them onto multiple lines and indent them a bit. If there was no line to separate the conditions from the subsequent execution statement, it would look pretty messy IMO:


      if ( (blah && (blah < abcdefghijklmnopqrstuvwxyz)) ||
            (blah && blah) ||
            blah )
      {
            blah = blahblahblah;
            blah++;
      }


      if ( (blah && (blah < abcdefghijklmnopqrstuvwxyz)) ||
            (blah && blah) ||
            blah) {
            blah = blahblahblah;
            blah++;
      }

      The second example does 'flow', which is nice to look at, but the fact that it is awkward to tell where the condition stops and the subsequent execution statement starts, is not so nice.

      --
      which is totally what she said
    105. Re:Some of those examples by Anonymous Coward · · Score: 0

      I used to use Allman in C# and PHP but then I started doing a lot of Javascript and ajax and some javascript interpreters don't like anything but cuddled '} else {' so I standarised on that in all algol languages.

      Because my eyes are looking for the whole '} else {' cluster the clause never seems to get lost to me.

      On the other hand the thing that really gives away the flow of the program is the indentation which is why I understand the way of Python.

    106. Re:Some of those examples by somersault · · Score: 1

      So you'd prefer your code if it were only occasionally split into paragraphs (say a newline and tab at the end of each if/for/while/whatever block, but nowhere else)? You're taking the argument to rather absurd extremes. The most convenient way to structure your code is somewhere in the middle of those two extremes, and I expect that a lot of people tend to go with what they are first taught.

      It is of course possible to change your coding style - I'd be much more interested to hear from those who have changed their styles and why, rather than just have people say "it makes more sense to me" or "I can read denser code fine, so obviously I'm smarter than those who find it less readable", etc.

      It's all down to whatever you are used to. Getting used to a different style of code is kind of like learning to drive on the other side of the road - and I'm sure some morons will have reasons for why their particular side of the road is better - but in essence there is no real difference, as long as everyone is driving on the same side. The worst case scenario would be someone changing coding styles every few lines.

      --
      which is totally what she said
    107. Re:Some of those examples by somersault · · Score: 1

      It doesn't look confusing to me at all, simply because I am used to it. The code in the else block is completely separate to the code that is going to be executed if the first set of conditions were true.

      An arbitrary example to perhaps make you think of the structure a bit differently (or, more likely, you'll just think I'm an idiot ;) )


      if (blah blah) do_something(); else {
              do_other_stuff();
              AndSomeMore();
              andSomeMoreStuff();
      }

      I bet further down the page there are arguments on StylesOfCapitalisationAnd_joining_together_words, I just decided to mess about with it there, I tend to use VariablesLikeThis in a wordy language like Delphi, and variables_like_this for more symbol oriented stuff like C.

      --
      which is totally what she said
    108. Re:Some of those examples by Hegh · · Score: 1

      I definitely agree for horizontal density. I find it much more difficult to read and understand a line like this:

      x=(acos(sin(theta+PI/2)+cos(phi-PI/2))+PI)/4;

      Than a line like this:

      x = (acos(sin(theta + PI / 2) + cos(phi - PI / 2)) + PI) / 4;

      In fact, I would probably split the line at the + between the sin and the cos, aligning the sin and cos vertically.

      But anyway, I find that vertical density makes much less difference. As a result, I prefer the "cuddled" version. But there is one inconsistency that I will sometimes use:

      // Comment describing the test
      if (...) {
      }
      // Comment describing the inverse of the test
      else {
      }

      But that is pretty rare, since usually the test is simple and its inverse doesn't need an explanation.

      --
      Bravery is not a function of firepower.
      ~J.C. Denton (Deus Ex)
    109. Re:Some of those examples by phred75 · · Score: 1

      I FUCKING HATE: if (condition) { } else { } OR any variation there of. It's: if (condition) { } else { } AND THAT'S IT! I WILL FIGHT YOU ALL!!!

    110. Re:Some of those examples by Rysc · · Score: 1

      Anything can be taken too far and every person is different.

      That said, ptrStupidVariableNamesPissMeOff. Things like capitalizing class names, or all caps for constants, whatever; cool by me. But camel casing variables and Hungarian notation annoy the hell out of me, no matter the language.

      </rant>

      --
      I want my Cowboyneal
    111. Re:Some of those examples by nuttycom · · Score: 1

      Ummm... I sort of see proper indentation as the solution to this problem, not wasted lines on the page.

    112. Re:Some of those examples by thetoadwarrior · · Score: 1

      If things are indented properly then it's no problem. If you happen to be a bit blind with code, open it up in Notepad++ and hit ctrl + T to find the other bracket. I think a lot of IDEs also provide similar support.

      I've never had an issue with it which isn't to say some don't but I find proper commenting and decent tabbing helps me learn someone else's code more than spreading things out even more vertically with the bracket it on its own line.

    113. 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.
    114. Re:Some of those examples by Quicksilver_Johny · · Score: 1

      As everyone should.

    115. Re:Some of those examples by EkriirkE · · Score: 1

      Umm... what?

      --
      from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
      to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
    116. Re:Some of those examples by sunderland56 · · Score: 1

      Otherwise
      writing
      like
      this
      would
      be
      much
      easier
      to
      read

      The idea of correct code formatting is to isolate concepts - not individual words. So more correctly you would have

      Otherwise
      writing like this
      would be much easier to read

      which is easy to parse.

    117. Re:Some of those examples by telbij · · Score: 1

      agreed!

    118. Re:Some of those examples by telbij · · Score: 1

      I'm aware of the optimal line length. It doesn't mean arbitrarily short though. It's easier to read something in a straight line, the reason long lines are a problem is because of visual tracking from one line to the next. It also enables speed reading because you can read in a whole line as a unit. One word per line makes speed reading impossible and requires just as much visual tracking as one super long horizontal line, but with slightly less efficient use of space.

    119. Re:Some of those examples by LarBabyDude · · Score: 1

      I agree. I am a C# developer/architect. I find that a little extra white space goes a long way. I also believe consistency is the most important. This includes naming conventions. For instance all of our methods in a class do NOT contain the name of the class. When reading the code it should kinda sound like english. The easier it is to read, the better. The more consistent it is across a team's code, the more easily Programmer A can maintain Programmer B's code. White space can help separate out important steps in a process. Visual highlights like //************** Public Methods ********* can help as well when the code for a class is several thousand lines long.

    120. Re:Some of those examples by jc42 · · Score: 1

      Hear! Hear! ... It is better to be consistent and wrong than to be inconsistent.

      Heh. I did work on one project where the style rules included one saying that all if commands had to have an else clause. This was in a language which, unlike C and perl, else clauses had to have at least one instruction. And the compiler was clever enough to produce a warning for simple instructions whose results weren't used. There were a lot of routines with a dummy global variable that was set to some random value in an else clause. Some programmers got quite clever in their ways to do nothing.

      Even more fun, the checkin code spotted ifs of the form "if (v = expr)" and quietly changed it to "if (v == expr)".

      The management wanted to protect us from common coding mistakes.

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    121. Re:Some of those examples by lsatenstein · · Score: 1

      I find that the editor is a great tool for matching braces, quotes, and any constructs that require matching. A good editor knows about nesting as well as comments.

      --
      Leslie Satenstein Montreal Quebec Canada
  2. Keep it simple! by Anonymous Coward · · Score: 0, Insightful

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

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

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

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

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

    7. Re:Keep it simple! by revengance · · Score: 1

      You could use a for loop?

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

    9. Re:Keep it simple! by SuperDre · · Score: 0, Interesting

      I fully agree, but ofcourse there are always exceptions.. If you need code that runs fast then it can be better to just copy&Paste (which isn't something people seem to care about these days anymore, and then complain about having to need a faster computer every now and then just to run the same kind of program).

    10. Re:Keep it simple! by Anonymous Coward · · Score: 0

      I teach programming. One of my common refrains in class is that if you have to cut and paste code you are probably doing something wrong. I suggest the student to take it as a signal to re-examine his/her design choices. The two most common results are (1) a new method (a.k.a. function) or (2) inheritance. However, sometimes we conclude that copy and paste is the best choice.

    11. 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;
      }

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

      -1, Dense

    13. Re:Keep it simple! by darknlow · · Score: 1

      Cloning is bad practice indeed but it is true that some times we can't avoid it. For instance, when you have to do with extremely static code, probably produced for safety critical applications where dynamic arrays or any other dynamic memory allocation is prohibited (SPARK), you might end up with chunks of code which are used more than once. Then you are trying to make these chunks as "dynamic" as possible so you can use them again with no big effort. Maintenance, in such cases might not the highest priority. A satisfactory enough proof of correctness would be.

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

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

    15. Re:Keep it simple! by mtinsley · · Score: 1

      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.

    16. Re:Keep it simple! by Bloater · · Score: 1

      Unless somebody commits the cardinal sin of cutting and pasting some code then interlacing the two differing contexts in among the pasted bit - and reordering the pasted bit.

      Now that is nightmare code. And it is all too common - especially among embedded developers (where embedded seems to be a synonym for who cares they're going to be stuck with us).

    17. Re:Keep it simple! by Anonymous Coward · · Score: 1, Funny

      My eyes! They burn!

    18. Re:Keep it simple! by kolicha · · Score: 1

      And with open source you'll eventually get:

      int multiply(int a, int b) {
      ....if (b < 0) {
      ........return multiply(a, b+1) - a;
      ....} else if(b > 0) {
      ........return a + multiply(a, b-1);
      ....} else {
      ........return 0;
      ....}
      }

      Which will may be made more efficient after this. Gotta love it :)

      Sorry about the code layout

    19. Re:Keep it simple! by StrawberryFrog · · Score: 1

      Yup - updating multiple bits of c+p code where the two are subtly different is a 'mare.

      Do both versions need to be updated? Do changes to one mean that the new fix is not applicable to to? Was the change to one version in fact a fix that should be applied out to the others? Can they be consolidated again? Should you rather just a find a blunt, heavy object and apply it to the original author instead?

      --

      My Karma: ran over your Dogma
      StrawberryFrog

    20. Re:Keep it simple! by Anonymous Coward · · Score: 0

      it wouldn't bust the stack, it would just go on forever. This is an infinite loop, not infinite recursion

    21. Re:Keep it simple! by kolicha · · Score: 1

      Edit: And see the stack overflow error when run with a big number. Maybe a coding standard should be don't use recursion when not needed; and don't try to be clever.

    22. Re:Keep it simple! by mounthood · · Score: 1

      Easier?!?


              if (!( a --> 0 )) goto done;

      It should be "(a-- > 0)"; no space between the "a" and the decrement operator.

      That's the sort of nasty bug you get with so called "structured programming". With the grandparents post everyone understands exactly what it's doing.

      --
      tomorrow who's gonna fuss
    23. Re:Keep it simple! by Anonymous Coward · · Score: 0

      I hope you're joking, because there should be 4 294 967 295 more lines. If you only allow positive numbers, you should be checking for the negative condition, and there should still be 2 147 483 647 lines.

    24. Re:Keep it simple! by Gnaget · · Score: 0

      How about just x = a * b;

    25. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Well, with the code provided, you could have just used a single:

          x = b*a;

      But more importantly, since that obviously wasn't the point, try a switch dipshit...

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

          switch (a) {
              case 1: // do something to x
                  break;
              case 2: // do something else to x
                  break;
              case 3: // do yet something else to x
                  break;
          }

          return x;
      }

    26. Re:Keep it simple! by The_Wilschon · · Score: 1

      Correction: see the stack overflow when you use a language that doesn't recurse properly.

      --
      SIGSEGV caught, terminating

      wait... not that kind of sig.
    27. Re:Keep it simple! by Anonymous Coward · · Score: 0

      you could write:

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

      for(int i=0;i < a;i++)
      {
        x +=b;
      }

      return x;
      }

    28. Re:Keep it simple! by 4D6963 · · Score: 1

      I hope you're joking as well. Each of the 2^32 possible values for 'a' gets de facto 4 lines. And for each the number of extra lines is 'a', which means the total number for the body of the function will be closer to f(M) = 4*M + M!

      If M is 2^32 then that would be... mmmh hold on.. calc.exe is having a tough time with (2^32)!

      However you might want to just avoid calculating the result of a*b is it's >= 2^31 anyways, so the real number of lines in that case is more complicated.. And that's assuming the intended range of my function anyways. Of course I made up the number because I wasn't trying to come off as like one of these guys from The Big Bang Theory, although this very post probably doesn't help with that...

      Hmmm..

      --
      You just got troll'd!
    29. Re:Keep it simple! by Anonymous Coward · · Score: 0

      int multiply(int a, int b)
      {
        int x = 0;
        for(int z = 0; z < a; z++)
          x += b;
        return x;
      }

    30. 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!
    31. Re:Keep it simple! by 4D6963 · · Score: 3, Funny

      How about just x = a * b;

      How about just WHOOOOOOSH!!

      --
      You just got troll'd!
    32. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Umm..

      int multiply(int a, int b) {
              int x = 0;
              for (int i = 0, i<a, i++) {
                      x += b;
              }
              return x;
      }

    33. Re:Keep it simple! by Anonymous Coward · · Score: 1, Funny

      That's the effect of global warming: frosted structured programmers resurface :-)

    34. 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!
    35. 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);
      }

    36. Re:Keep it simple! by Anonymous Coward · · Score: 0

      more syntactical sugar!!:

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

    37. Re:Keep it simple! by aldousd666 · · Score: 1

      I like how you used the += operator so the code is much more efficient and readable.

      --
      Speak for yourself.
    38. Re:Keep it simple! by 4D6963 · · Score: 1
      OK, seriously, what the hell is wrong with you guys. If the content of my comment didn't make it clear enough (or too subtle, if it was even subtle) that it was a sarcasm, and that the +5 Funny moderation wasn't a big enough clue, you could have at least seen the half dozen other replies that were only slight variations of the very code you just posted, or even all the other replies that made it clear enough it was originally a joke.

      Or were you too eager to demonstrate your 1337 coding skills you straight jump on the reply button and started coding like the wind?

      --
      You just got troll'd!
    39. 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.
    40. Re:Keep it simple! by I+cant+believe+its+n · · Score: 1

      However, sometimes we conclude that copy and paste is the best choice.

      Cut'n'paste is funnier if you are several people working on the same project.

      Gives new meaning to the phrase 'someone stole my code'.

      --
      She made the willows dance
    41. Re:Keep it simple! by jeremyp · · Score: 1

      Ahh thanks.

      I was going to ask what language the code fragment was written in because I've never seen a --> operator.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    42. Re:Keep it simple! by hansamurai · · Score: 1

      Even Eclipse can do it, just found that feature the other day.

    43. Re:Keep it simple! by dawsdesign · · Score: 1

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

    44. Re:Keep it simple! by 4D6963 · · Score: 1

      Yay... too bad a dozen people already beat you to it (both writing more efficient code and missing the joke).

      --
      You just got troll'd!
    45. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Why not?

        x = a*b;

      Developers re-inventing the wheel again, huh?

    46. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Optimized for RISC I assume? Awesome!

    47. Re:Keep it simple! by colmore · · Score: 1

      I think the fact that I only make friends with people who have senses of humor just blinds me to the fact that there are people out there who don't have them.

      It's strange. Er, "dipshit."

      --
      In Capitalist America, bank robs you!
    48. Re:Keep it simple! by colmore · · Score: 1

      memory is so much slower than processing these days that old-school tricks like unfurling loops actually slow down code as the larger executable has to be paged into cache more frequently.

      --
      In Capitalist America, bank robs you!
    49. Re:Keep it simple! by colmore · · Score: 1

      If your coding practice requires a *proof of correctness* you're operating in a different world from what this ask slashdot is even about.

      Are you modeling ballistics fro DARPA? Do they even prove their code? Does it happen outside of academia these days?

      I know someone is working on a proof for the L4 kernel. That's the only real world use of formal proof I've heard of this decade.

      --
      In Capitalist America, bank robs you!
    50. Re:Keep it simple! by Joe+U · · Score: 1

      Now, for 10 bonus points, write that in Commodore 64 BASIC.

    51. Re:Keep it simple! by AlexSons · · Score: 1

      I consider goto (like some before me) obsolete and its use obnoxious. This function screams for a simple for-loop. I know it is possible to use fewer local variables and a little less arithmetic. Probably there is also a more elegant recursive solution, however tending to be less readable and more error-prone. Coding-quality should prevail above beauty and elegance? SOLUTION EXAMPLE int multiply( int a, int b) { int x=0; // define local variable int y=1; // define local variable if (!( a > 0 )) return -1; // short noted version of for-loop (i.e.: for (expression) {statement} ) is against aforementioned JSF coding principles // long noted version of for-loop with whitespace follows below for (y=1; y=a, y++) { x+=b } return x; }

    52. Re:Keep it simple! by AlexSons · · Score: 1

      (Ayee, my regrets: my former reply was added as HTML where it should have been plain-old text.)

      I consider goto (like some before me) obsolete and its use obnoxious.

      This function screams for a simple for-loop. I know it is possible to use fewer local variables and a little less arithmetic. Probably there is also a more elegant recursive solution, however tending to be less readable and more error-prone. Coding-quality should prevail above beauty and elegance?

      SOLUTION EXAMPLE

      int multiply( int a, int b)
      {
            int x=0; // define local variable
            int y=1; // define local variable
            if (!( a > 0 )) return -1; // short noted version of for-loop (i.e.: for (expression) {statement} ) is against aforementioned JSF coding principles // long noted version of for-loop with whitespace follows below

            for (y=1; y=a, y++)
            {
                  x+=b
            }

            return x;
      }

    53. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Morons.

      #define mul(a, b) (a*b)

    54. Re:Keep it simple! by jimmydevice · · Score: 1

      Came here for the recursion, Stayed for the +5 Funny.

    55. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Arrrrrggghhhhhhh!!! haven't you heard gotos are evil?

    56. Re:Keep it simple! by Anonymous+Brave+Guy · · Score: 1

      And for bonus points, attempting to multiply by 0 probably yields an overflow. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    57. 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.
    58. Re:Keep it simple! by Anonymous Coward · · Score: 0

      I hope it's a joke. Anyway I would do something like:

      int multiply(int a, nt b)
      {
      if( a == 0 || b == 0 )
        return 0;
      bool sign = true; //false == negative
      if( a 0 )
      {
        sign = ( sign )? false : true; //essentially just "switch"
        a = -a;
      }
      if( b 0 )
      {
        sign = ( sign )? false : true;
        b = -b;
      }
      int result = 0;
      for( int i = 1; i = a; ++i)
      {
        result += b;
      }
      if( !sign )
      {
        result = -result;
      }
        return result;
      }

      Which does essentially the same without any copying. :P

    59. Re:Keep it simple! by Anonymous Coward · · Score: 0

      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.

      How about to use a for statement ;)

    60. 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
    61. Re:Keep it simple! by Anonymous Coward · · Score: 0

      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.

      How about to use a for statement ;)

      GOTO HARMFUL ;-)

      How about this

      int multiply(int a, int b)
      {
                      int i;
                      int x = 0;
                      for (i = 0; i b; i += 1)
                      {
                                      x += a;
                      }
                      return x;
      }

      Much easier and more maintainable than a weird goto :-P

    62. Re:Keep it simple! by SuperDre · · Score: 0

      Uhm.. yeah, we also did get much faster results by just putting the code back into the routine instead of splitting it up into little functions.. But knowing when to use fast code and when to use 'slow-but-better readable' code is something everybody must decide for him/herself, IMHO due to the faster machines people tend to get lazy and therefore we still keep needing faster and faster machines just to run the same program at the same speed as the previous version.. But just to quote one of my favorite characters: 'Opinions are just like assholes, everybody's got one'..... So what you think is a good way of doing code doesn't mean it is for somebody else... (me included).. Just format your code as you think will make your life easier when you need to revisit your code, that's the most important thing...

    63. Re:Keep it simple! by incripshin · · Score: 1

      int multiply(int a, int b)
      {
              int x = 0;
              switch (a) {
              case 2: x += b;
              case 1: x += b;
              case 0: x += b;
              }
      }

      Still copy and pasting, but the code is simpler, easier to c+p, and more efficient. Isn't it just beautiful? :)

    64. Re:Keep it simple! by kramulous · · Score: 1

      But what if a or b is equal to negative zero?

      --
      .
    65. Re:Keep it simple! by davidbofinger · · Score: 1

      Repeated addition is inefficient. It would be faster to find the prime factors of a and b, sum the exponents and multiply the powers together.

    66. Re:Keep it simple! by mikael · · Score: 1


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

      x += b * (a== 1) + (b

      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    67. Re:Keep it simple! by Anonymous Coward · · Score: 0

      #include "disclaimer.h"
      #define ST smaller than symbol

      Actually, as far as I am concerned, a better implementation would
      avoid the goto statement completely. I would also use a for loop,
      exploiting the possibilities of the C language.

      First version (relies on the multiplication operator and slow):

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

              for (TempInt = b; TempInt ST (a * b); TempInt += b);

              return TempInt;
      }

      Second version, without multiplication operator:

      int multiply(int a, int b)
      {
              int TempInt = b;
              int Counter;

              for (Counter = 1 ; Counter ST a ; Counter++)
              {
                      TempInt += b;
              }

              return TempInt;
      }

      That was my grain of salt, please feel free to ignore it.
      Note that

      "disclaimer.h" // These are my opinions and should not be taken as // expressing which way to do, but which way I prefer

    68. Re:Keep it simple! by dawsdesign · · Score: 1

      Right you are... I guess I'm not that adept at navigating through slashdot comments :( At least there's no GOTOs!

    69. Re:Keep it simple! by complete+loony · · Score: 1

      Cut-and-paste is a useful refactoring tool. It allows you to quickly move sections of code around. It's copy-and-paste that causes obesity problems.

      --
      09F91102 no, 455FE104 nope, F190A1E8 uh-uh, 7A5F8A09 that's not it, C87294CE no. Ah! 452F6E403CDF10714E41DFAA257D313F.
    70. Re:Keep it simple! by Anonymous Coward · · Score: 0

      If C had a more powerful macro system, you could do something like this:

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

              #define add(n) #if (n>0) x += b;
              #define mult(n) #if (n>0) mult(n-1); if (a==n) {add(n)} #endif

              mult (MAXINT)
      }

      ;-)

    71. Re:Keep it simple! by colmore · · Score: 1

      Opinions are like assholes...

      the entire internet has seen mine.

      --
      In Capitalist America, bank robs you!
    72. Re:Keep it simple! by 4D6963 · · Score: 1

      When do we get the rest? And wtf is (a==1) even supposed to be for?

      --
      You just got troll'd!
    73. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Coping & Pasting does not mean you cannot write some "ifs" one after other. Belive me I was working on a maitaning of a program which have a lot of the copied parts.
      To change one easy thing, I need to change it in a lot of places. After found a bug in one part I need to fix it in many places and it was hard to test every other places where the bug could occure.

      It is hard to explain your manager what took you so long... Certainly the program was written very fast.

    74. Re:Keep it simple! by Anonymous Coward · · Score: 0

      static long multiply(long a, long b)
      {
                      long ret;
                      asm("mul %0, %1" :(a), (b) :(=ret));
                      return ret;
      }
      or something like that

    75. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Prolog has --> as a built-in operator which has something to do with grammar rules. Look it up if you're interested.

      However, the rest of the code doesn't look remotely like Prolog.

    76. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Why in the world would anyone do that?

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

        while(a)
        {
          x+=b;
          --a;
        }
        return x;
      }

    77. Re:Keep it simple! by 4D6963 · · Score: 1

      WHOOOOOOOOOOOOOOOOOOSH!!!!

      --
      You just got troll'd!
    78. Re:Keep it simple! by chunkyq · · Score: 1

      int addone(int a) {
      return a+1;
      }

      int subone(int a) {
      return a-1;
      }

      int add(int a, int b) {
      if (b == 0) return a;
      else if (b > 0) return(add(addone(a), subone(b)));
      else return(add(subone(a), addone(b)));
      }

      int mult(int a, int b) {
      if (b == 0) return(0);
      else if (b > 0) return(add(a, mult(a, subone(b))));
      else return(add(-a, mult(a, addone(b))));
      }

    79. Re:Keep it simple! by andi75 · · Score: 1

      Not only that, the overflow check is missing from all of the above examples. Here's the proper way:

      Multiply contents of $c000, $c001 and store the result in $c002, $c003, little endian.
      LDX $c000
      DEX
      BPL nozero
      LDA #$00
      STA $c002
      STA $c003

      nozero:

      LDA #$00
      ADC $c001
      STA $c002
      BCC nocarry
      LDA #$01
      ADC $c003
      STA $c003

      nocarry:

      DEX
      BPL nozero

      Ofc. this should be optimized by using bit-shifts, and is probably buggy since I haven't used 6502 assembly for at least 2 decades.

    80. Re:Keep it simple! by andi75 · · Score: 1

      I see at least 2 bugs right after posting, go find them.

    81. Re:Keep it simple! by Just+Some+Guy · · Score: 1

      That does not address the duplication of "=".

      --
      Dewey, what part of this looks like authorities should be involved?
    82. Re:Keep it simple! by Anonymous Coward · · Score: 0

      a loop...

    83. Re:Keep it simple! by Anonymous Coward · · Score: 0

      I for one welcome the a --> 0 syntax !

    84. Re:Keep it simple! by Setsquare · · Score: 1

      Actually it (thanks to 2s complement arithmetic) gives the right answer. "A" decrements down to MIN_INT then wraps round to MAX_INT then decrements all the way down to 0. It effectively calculates the unsigned equivalent of "a" (being 2**32 -a) times "b". The result of that is b*2**32 - b*a. The first part doesn't fit in your int, so you're left with -b*a. Of course, if you have 64-bit ints you may have wait a few decades.

    85. Re:Keep it simple! by jZnat · · Score: 1

      That's just using iterative recursion which is just as easily represented as a loop in a language like C. :)

      --
      'Yes, firefox is indeed greater than women. Can women block pops up for you? No. Can Firefox show you naked women? Yes.'
    86. Re:Keep it simple! by Anonymous Coward · · Score: 0

      Clearly, the solution here is a select() statement.

    87. Re:Keep it simple! by DavidHumus · · Score: 1

      x= a*b;

    88. Re:Keep it simple! by Anonymous Coward · · Score: 0

      I think I heard cut and paste is the source of most bugs. I may be wrong, but it is a big source of bugs.

      However, I just cannot bring myself to type the same two or three lines just to change one variable name. I cut, paste, and change the variable. And, no, using a function for 2 or 3 lines is not necessarily appropriate either.

      So, I've learned to live with this issue. Every time I cut and paste, I remind myself that I am doing something error prone and I take a little extra time to make sure I've replaced what should be replaced. Surely I can find my mistakes if I pay attention (... he thinks arrogantly)!

      Interestingly, this has not eliminated my cut and paste mistakes. I still find that, even after what I thought was a careful review, I'll occasionally find something I forgot. So, I often double check my cut and paste work. Interestingly, I have found mistakes even after a double or triple check!

      Moral of the story: cut and paste is extremely error prone and yet we continue to do it because there is something in human nature (arrogance?) that makes us think we will clearly recognize our own mistakes if we just look a little closer (or that only other people are dumb enough to miss a mistake after triple checking)

      I also think there may be a mental bias of assuming code that has been cut and pasted is correct because it was correct before it was copied. Really, our brain needs to invalidate the assumed correctness bias when that code is copy and pasted ... but that does not come naturally.

    89. Re:Keep it simple! by Bob+Gelumph · · Score: 1

      He said Cut and Paste, not Copy and Paste. He means keep it neat enough that it can be refactored easily, I think

      --
      I'm gonna need a spec.
  3. 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 cayenne8 · · Score: 1

      You know...I don't think I've worked in a place that really HAD any standards you had to follow for coding. Maybe it is more prevalent in the private sector? I've been mostly on govt/DoD contracts, and I've never been asked to follow any real standard...

      --
      Light travels faster than sound. This is why some people appear bright until you hear them speak.........
    2. 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'.

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

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

    5. Re:Space Usage by SunTzuWarmaster · · Score: 1

      I work in the Gov/DoD world with a few contractors (CSS), and we have fairly precise coding standards. Hungarian notation, no multiple return paths, modulated code, etc.

      Because of this, if you want to develop a completely new program, it is quite easy. You take the Thread-safing class, the logging class, the TCP/IP server class, and the QT GUI class and you have yourself a quick networked threaded test application in less than a day (a week if you are an intern).

    6. Re:Space Usage by mikeabbott420 · · Score: 1

      2. Make it look like all the other code in our system where I am the people that set the original, still used (*), coding style are 15+ years gone. *some minor changes as we stopped formatting for 80 columns

      --
      This program was made possible by a grant from the Ultra-Humanite, and viewers like you.
    7. Re:Space Usage by fractalVisionz · · Score: 1

      This is actually one of the smartest things ever said. I, for one, see this all the time in the code at my company; nested switch statements (of which a single case is 1000+ lines, and the total lines in the switch is 3000, yikes!) and endless if statements (some as deep as 10 levels). What this does is produce a deeper cyclic count of the code, making it very hard to read, understand, and maintain.

      A great way to work on this is to remove the else, or even the if clause. For example, change (to remove the if clause, just think of the first if saying if (x != NULL) { and without the break; statement):
      while (some condition) {
              if (x == NULL) {
                    Do something...
                    break;
              } else {
                    Do something else...
              }
      }

      Could easily become:
      while (some condition) {
              if (x == NULL) {
                    Do Something...
                    break;
              }

              Do something else...
      }

      Though this example is really simple, if you have many control statements in the "Do something else..." part, you can really see where this would help.

    8. Re:Space Usage by Gorobei · · Score: 1

      Yeah. I run screaming from any system that doesn't have intellectual owners (the people who wrote it, or current developers enhancing it,) or has owners that don't like it. I'm trying to kill off one of these beasts right now - the users hate it, the only developers left are $1000/day "consultants," and it's 5 years out of date with respect to business needs. I feel a little bad for all the people who have built a "career" around supporting this hell-spawned beast.

    9. Re:Space Usage by KlaymenDK · · Score: 1

      I notice that you don't say whether this is good or bad. :) Having all coders actually remember all the code sounds like a great productivity booster and backup plan. But the initial 'cost', oy veh.

    10. Re:Space Usage by TheLink · · Score: 1

      I suppose that's true in general.

      But if you can't rewrite messy code so that it's not messy, please leave that mess in one place rather than spreading it into 3 or more _one_use_ "artificial" functions created just to "tidy" things up.

      If those functions make sense to other people and not just you, then fine. Otherwise, let's forget about checkThingyA() ok?

      --
    11. Re:Space Usage by NormalVisual · · Score: 1

      I feel a little bad for all the people who have built a "career" around supporting this hell-spawned beast.

      At a thousand bucks a day, I feel more envy than anything.

      --
      Please stand clear of the doors, por favor mantenganse alejado de las puertas
    12. Re:Space Usage by Anonymous Coward · · Score: 1, Funny

      I'm trying to kill off one of these beasts right now - the users hate it, the only developers left are $1000/day "consultants," and it's 5 years out of date with respect to business needs.

      So you are trying to get rid of Windows XP?

    13. Re:Space Usage by jeremyp · · Score: 1

      Oh god no, that is so wrong.

      And you have so missed the point.

      You haven't got rid of the complex structure, you have only obscured it. Not only that, but the break obfuscates the loop post condition.

      My coding standards would completely ban the use of continue and only allow break in switch statements.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    14. Re:Space Usage by honkycat · · Score: 1

      Good comment. IMO, a requirement (necessary, probably not sufficient but close) for creating a function out of a chunk of code is that its behavior be describable in English (or your human language of choice). That is, a function should do something meaningful in a higher level way. "Meaningless" logical bit-twiddling should be kept within functions.

      I think it's ok if the function is only called once, as long as this criterion is met. This tends to cause things that are functions to be things that are reasonably likely to be used again; they're at least chunks that would show up in pseudo-code.

    15. Re:Space Usage by colmore · · Score: 1

      Some shops hire 4 or 5 very very good programmers and just give them freedom.

      Some shops have dozens or hundreds of coders of more market-average skill.

      Coding practices are for the latter. I'm sure Bell Labs let their guys write any damn kind of code they wanted. I can't imagine the team at PARC getting told by management where to put their braces and semicolons. I'm sure the MIT AI lab didn't worry over stupid nitpicky...

      or wait... Stallman was there.

      --
      In Capitalist America, bank robs you!
    16. Re:Space Usage by fractalVisionz · · Score: 1

      You haven't got rid of the complex structure, you have only obscured it. Not only that, but the break obfuscates the loop post condition.

      I have not missed the point. I gave an overly simple example because I hate typing code into comments. My point was that most of the time it is better to break up an if/else if/else statement if the main (and large) part of the code is only in the else, and the rest is in a one or two liner in the if/else if. This way, most of the main code isn't so far indented and thus easier to trace and maintain.

    17. Re:Space Usage by funfail · · Score: 1

      There is no guarantee that your uber-creative code won't be maintained by "normal" people in the future. Coding standards are for everybody.

      If you are writing software for yourself, go ahead and write obfuscated Perl. But if you write for somebody else, please adhere to some kind of standard.

    18. Re:Space Usage by Kjella · · Score: 1

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

      I'd call an exception to that when it fits in a screen length. I've run into some where I'm basicly nesting 4-6 loops but the "meat" is just to call doFoo() on each item. I'd say it's mostly a bad idea though, sure.

      --
      Live today, because you never know what tomorrow brings
    19. Re:Space Usage by MichaelSmith · · Score: 1

      book-length horrors created by people so incompetent that management didn't trust them to write code.

      My first boss only knew FORTRAN, but we were working in Pascal. So the coding standard was don't do anything you can't do in FORTRAN.

    20. Re:Space Usage by Anonymous Coward · · Score: 0

      Heh, nothing like accountability and semi-public humliation to get people to fix their code or write it decent before committing it ;-)

      A certain UNIX programmer of famous yore once said, he was writing the "BUGS" section of the manual and then went back to fix the code, because he couldn't let it pass after reading the "BUGS" section ^_^

    21. Re:Space Usage by jc42 · · Score: 1

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

      But you've missed something important in the discussion: Coding standards are rarely if ever produced by the agreement of the programmers. They are almost always decreed by managers who don't do the coding. When there's an official coding standard, it's not "Do you agree with this?" It's usually "These are the rules, and you will follow them."

      Of course, most of the other people here seem to have missed that, too. Most of the messages so far have been people saying "I like this format, therefore everyone should use it." But in most organizations, you only get to say that if you're at a managerial level with power over the programmers. If a mere programmer says such things, the only result will be that other will reply with their favorite style (which everyone else should use). And that doesn't lead to any agreed-upon rules, except in the statistically unlikely case that every programmer likes the same format.

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    22. Re:Space Usage by try_anything · · Score: 1

      Coding practices are for the latter. I'm sure Bell Labs let their guys write any damn kind of code they wanted. I can't imagine the team at PARC getting told by management where to put their braces and semicolons.

      The team at PARC didn't have to be told where to put their braces and semicolons, because they were smart enough to know already: you put the braces and semicolons wherever is consistent with the existing code in the project.

      Even the GNU style guide says:

      If you are contributing changes to an existing program, please follow the style of that program.

      I've worked in corporations where coding guidelines were adopted. Coding guidelines sound pretty ambitious and draconian, and they may be sweated and obsessed over by the committees that produce them, but in my experience, they exist solely as an excuse to crack down on really gross offenders, such as people who contribute inconsistent code to existing projects or randomly reformat existing source files.

      You need a bureaucratic tool like coding standards because sometimes the moronic offenders are at the managerial level or have staunch managerial support. "He's a real star; I just let him do his thing and get out of his way." Uh, yeah, if he's such a star, why does he reformat every code file he checks in? Can this "star" not figure out how to edit a source file without reformatting it to match the default indentation style of his IDE?

      So in my experience corporate coding standards are applied only to the most egregious dumbasses in a corporation. Even low-level corporate drones can get away with violating corporate coding standards if they observe basic common sense and common courtesy.

      It only stands to reason. The vast majority of code in any corporate codebase was written before the current standards were put in place, so it's inevitably a hodge-podge of coding styles. If your project doesn't follow the guidelines, people will just assume it grew from a codebase that existed before the guidelines were adopted.

    23. Re:Space Usage by Alphasite · · Score: 1

      just because a sentence FOLLOWS another doesn't mean there's causality there, you know?

      "I writte messy code nobody understand but that works.

      Because of this, if you want to develop a completely new program ..."

      So one thing is about having good REUSABLE code and a completely different thing to have readable code...

    24. Re:Space Usage by dkf · · Score: 1

      My coding standards would completely ban the use of continue and only allow break in switch statements.

      That coding style tend to end up with a complex nest of flag variables just so that you can signal the right sort of ending condition. Or maybe now that you've found what you were looking for you continue through that list just so that you can keep your loop condition simple? I've seen both in real code, and they don't make life easier. I prefer the solutions that keep code both short and shallow. (Well, as short and as shallow as possible given the algorithm needed at that point; if it needs 4 nested loops, so be it.)

      Bah, it looks like you and I emphasize totally different things. Bet you're not an "80 column" guy...

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    25. Re:Space Usage by xouumalperxe · · Score: 1

      I have to deal with the same. Standard ABAP coding style involves each function parameter being in a separate line, with functions often having 10-15 input and output parameters total, and our standard issue 15", 1024x768 laptop displays having very little screen real estate.

    26. Re:Space Usage by xouumalperxe · · Score: 1

      If/Else constructs exist to make it clear that you're alternating between two scenarios. The two code snippets you gave us both had the switching happening, except that the original version has that switching made patently clear by an explicit "else", whereas your proposed "improved" version makes it so that a cursory read through the code will miss the break and make the reader assume that normal flow will reach the second part of the code unconditionally.

    27. Re:Space Usage by rootooftheworld · · Score: 1

      +1 Sadly Insightfull

      --
      I know full well that tobacco is bad for you, so I smoke weed with crack
    28. Re:Space Usage by Anonymous Coward · · Score: 0

      I think what he was trying to say was that some things should not be place in else blocks where they should be normal flow. For this he is correct. Many times programmers decide that something should be in an else statement just because there is an if statement, which is incorrect. Yes, for the use case with loops, this can be generally incorrect, but what the gp was trying to say was if the main code flow is in an condition, where it really shouldn't be, then take it out.

      I think everyone is attacking the gp because of the while statement, but missing the point of what the gp tried to say, the main part of the code does not always have to be inside the else, or even the if statement. When you can break it out, it usually (maybe for you all not with the while case) becomes more maintainable.

    29. Re:Space Usage by Firehed · · Score: 1

      They are almost always decreed by managers who don't do the coding.

      This kind of thing never ceases to confuse me. While I've never coded underneath anyone else (though I have some quite sizable solo and 2-3 person projects), I don't think I could possibly understand why managers would be touching the code in any way whatsoever. Tell me what you need done, what it needs to do, and what you're planning going forward so that I can plan accordingly, and let me get on with it. If they've got the time to be concerned over line placement of braces, hopefully they'll soon be found redundant by their managers.

      --
      How are sites slashdotted when nobody reads TFAs?
  4. 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 paradxum · · Score: 1

      I honestly agree with that for most code. The only exception is when using php for simple page area selection such as:

      blah blah blah html
      <? if($something){ ?>
      more html
      <? } else { ?>
      some other html
      <? } ?>
      end/footer html

      but rules were made to be broken right?

    2. Re:braces by kauos · · Score: 1

      I agree! It annoys the crap out of me too. In theory the reason is so that when you hotkey (Vim : Shift+5) from the close brace to the open brace, you don't have to move one more line up to see the condition statement. But in all honesty I just don't notice that as an issue. Its more important to have nicely laid out code (ie open brace on a new line), rather than have the hotkey work more efficiently.

    3. Re:braces by Hermel · · Score: 1

      Why? Is there a 'better' alternative?

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

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

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

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

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

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

    11. Re:braces by thogard · · Score: 1, Interesting

      That depends on how you parse the closing }. I have no problem wrapping my head around if foo then stuff else other stuff. I don't need it to sick out with extra special formatting.
      Most people have an innate basic built in "light" ignore for it since it doesn't matter unless your focusing on the statement lists after the else.
      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.

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

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

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

      The code is important. The braces are syntactical sugar.

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

    17. Re:braces by elronxenu · · Score: 1

      I can't stand seeing 'if' with no whitespace before the opening parenthesis, as in 'if(condition)'.

      'if' is not a function! (at least not in perl nor C).

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

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

    20. 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.
    21. Re:braces by Anonymous Coward · · Score: 0

      And it drives me nutters to see it the other way.

      if( condition ) {
              statement;
      }
      else {
              do something else;
      }

      so ... probably is personal preference too.

    22. Re:braces by __aapbzv4610 · · Score: 1

      that's actually how I code in c++. keeping the opening braces with the opening statement is how I code in Java. both ways have to do with the coding standards where I work.

    23. Re:braces by Anonymous Coward · · Score: 0

      Dont you mean %? % has been working in vi, ex and other editors for close to 30 years.
      Do you still use wq! when x! has been doing the same thing for every version of vi for at least 25 years too?
      x! is not ambiguous but does wq! mean (w)q! or w!q?

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

    25. 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.
    26. Re:braces by guycouch · · Score: 1

      Try this: blah blah blah html more html some other html end/footer html

    27. Re:braces by __aapbzv4610 · · Score: 1

      and that's a completely valid point. I'm saying I don't like seeing braces a certain way, just as you don't like the spacing with conditional statements a certain way. I never said anywhere that one was right or wrong, just I personally don't like seeing it one particular way.

    28. Re:braces by fictionpuss · · Score: 5, Funny

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

    29. Re:braces by guycouch · · Score: 1

      ... maybe I should try the preview button.

      blah blah blah html
      <? if($something): ?>
      more html
      <? else: ?>
      some other html
      <? endif; ?>
      end/footer html

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

    31. Re:braces by kauos · · Score: 1

      In practice debugging html templates with integrated jsp/php code (I started as a JSP developer) is not really that much harder than debugging straight java code. Its just what you're used to. And in fact for a LOT of smaller web applications it is the quickest, simplest and easiest way to get the job done. I think you're being a bit harsh knocking the use of conditional PHP statements in html code.

    32. 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
    33. 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
    34. 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.

    35. 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
    36. Re:braces by Anonymous Coward · · Score: 0

      This is the only one of the styles which would actually drive me insane.  Still probably let it go if it was consistent and worked

      Most styles in the style war want the braces in the outer scope thus I expect one of the following:

      //my typical style, empty line above if (or this comment line if included) and after else's '}'
      //to partition from the main block
      if(isValid){
          statement;
      }
      else{
          statement;
      }

      //Other styles I will read without questioning the coder's style:

      //fully written out
      if(isValid)
      {
          statement;
      }
      else
      {
          statement;
      }

      //else in brackets
      if(isValid){
          statement;
      } else {
          statement;
      }

      //mix match (I'd assume more than one person however.. or blindly copied code and
      //risk of bugs)
      if(isValid)
      {
          statement;
      } else {
          statement;
      }

      ...

      the things I will hand you back the code for unread if I can:

      //wrong tab depth
      statement
          statement

      //double close
      else{
          list of statements;
      }
      }

      //missed indent
      if(isValid){
      statement

    37. Re:braces by thogard · · Score: 1

      And according to the parser, that has nothing to do with the indenting, line spacing or in some cases the curly braces. My take on a code is it has to be understood at several levels and one of those is a higher level where such things are trivial all the way down to knowing that the sub brace has been added so they can put a extra variable on the stack. Remember in C the {} does mean "create a new stack frame" as well as grouping.

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

    39. Re:braces by thogard · · Score: 0

      if is functional in C and it always has been.
      if(foo) gets reduced to "test(foo)" followed by a "jump if NE" in most cases with nearly every CPU out there.

    40. Re:braces by tolomea · · Score: 1

      It scares me to think that you need to have the whitespace indicate this fact to you.

      The syntax highlighting, presence of braces and presence of an extra level of indentation on the next line don't cover it?

      By the way, sizeof, not a function either, it's actually an operator, but I'm willing to bet that you'd object strongly to writing "sizeof(bob)" as "sizeof bob".

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

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

    43. 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.
    44. Re:braces by Anonymous Coward · · Score: 0

      I prefer:

      if (exp) {
      } else {
      } ...but working at a place which has hundreds of branchs under version control they came to the standard:

      if (exp)
      {
      }
      else
      {
      } ...in order to cut down on merge errors. It makes a lot of sense in their situation, but I'll stick with the former for my own projects - I'd rather see more lines of code.

    45. 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
    46. Re:braces by paulatz · · Score: 1

      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.

      I found it difficult to follow the flow of a program when I have to scroll up/down a lot. Hence I try very hard to save vertical space, e.g. with this kind of syntax:

      for(i=0;i<10;i++) {
      for(j=0;j<10;j++) {
      ...
      } }

      In this way I can save an extra indentation level (so I can use longer lines), and one line

      --
      this post contain no useful information, no need to mod it down
    47. Re:braces by Anonymous Coward · · Score: 1, Interesting

      I hate that but the one I loath with all my strength is the braindead GNU standard:

      if (something)
          {
              do_something();
              for (;;)
                  {
                      something();
                  }
            }
      else
          {
              bla();
          }

      I mean wtf is that supposed to accomplish, making the code visually uglier and harder to follow at the same time!? If you have a page of code like that it's a real pain to match braces at a glance.

    48. Re:braces by Anonymous Coward · · Score: 0

      I prefer

      (something ? do_something : do_something_else)();

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

    50. Re:braces by pablomme · · Score: 1

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

      I do that when I write Javascript. The reason is that I'm used to Fortran, where you write

      if(condition)then
        statement1
      else
        statement2
      endif

      Similarly when I write bash scripts I do

      if condition ; then
        statement1
      else
        statement2
      fi

      (of 'condition && statement1 || statement2' if it fits in one line and statement1 always exits with 0).

      It's just a matter of what language you're used to in the first place; then you try to make other languages look like that one.

      --
      The state you are in while your HEAD is detached... - wait, what?
    51. Re:braces by Anonymous Coward · · Score: 0

      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;
      }

      That's because space in a textbook costs money.

      Unfortunately, putting the opening brace on the same line as the conditional clause makes it hard to find the end of the conditional clause and the beginning of the compound statement when the conditional clause is more than one line long.

    52. 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.
    53. Re:braces by Anonymous Coward · · Score: 0

      If you have a decent editor, it will match up braces for you. I coded when most terminals were 24x80, and the waste space from putting (especially opening) braces on lines by themselves made the code impossible to read - but there was a simple fix. I had emacs macros, unfortunately now lost, that collapsed and expanded the braces onto their own lines.

    54. Re:braces by TheRaven64 · · Score: 1

      Which has what, exactly, to do with my comment? There are sound reasons beyond screen space for breaking long lines. Studies have shown that for maximum readability a line should contain 66 letters, and so much longer than 80 columns leads to difficulty for the human brain to follow.

      --
      I am TheRaven on Soylent News
    55. Re:braces by Anonymous Coward · · Score: 0

      The code is important. The braces are syntactical sugar.

      And the human minds that need to understand that code see patterns, not code.

      So no, code layout is not "syntactical sugar" any more than using "int overflowCount" instead of "int xyz124c" is.

    56. Re:braces by Anonymous Coward · · Score: 1, Insightful

      Wow, Whitesmiths style! Afraid if I saw a commit formatted like that the memo wouldn't be very polite. K&R (function braces get newlines) and any of these are fine by me:

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

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

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

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

    57. Re:braces by Anonymous Coward · · Score: 0

      I prefer

      (something ? do_something : do_something_else)();

      I love that! It's clear, concise, and one line. It decides which function to call, then calls it.

    58. Re:braces by Javagator · · Score: 1

      Lines are cheap

      Here's how I do the braces thing. The braces line up, plus you don't "waste" a line (making your code shorter and more likely to fit in your window). However, I don't know anyone else in the Universe who codes like this, and I can't figure out why.

      if (condition)
      { statement1;
        statement2;
      }

    59. 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'
    60. 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.
    61. Re:braces by Anonymous Coward · · Score: 0

      I do the same thing, with the braces on their own line and same indentation. This lets you easily see what if statement the block belongs to and where it begins and ends.

      I always put the code in braces, even if it is one line and doesn't need it. I've added more code to a one-line if statement without adding braces too many times.

      I was surprised that my employer had this, and many other of my own coding practices, as their required practices. There were some that I never heard of, but adopted as my own. The document that had these even had the rational behind all of them. This was obviously written by a very good programmer and not management.

    62. Re:braces by welsh+git · · Score: 1

      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;
      }

      This will be totally unpopular, but the thing in your example that strikes me as worse is not having the open and closing braces in the same column. No-one else seems to, but I prefer:

      if (condition)
          {
              code-block-1;
          }
        else
          {
              code-block-2;
          }

      That seems much more obvious to me.. If you need to debug, you can also get a good feel for missing brackets with:

      egrep '{|}' x.c

      --
      Sig out of date
    63. Re:braces by Haeleth · · Score: 1

      But that's so wasteful!

      Try:

      for(i=0;i<10;++i)for(j=0;j<10;++j){
      ...
      }

      Uses less vertical space and saves a whole pair of braces. What's not to like?

      (Actually I'm in the "{ on same line, } on own line" school, because God told me in a dream that that's the only formatting style He approves of, and those who do anything different will burn for all eternity in Hell with all the wicked users of vi.)

    64. Re:braces by __aapbzv4610 · · Score: 1

      fair enough.

    65. Re:braces by KostasPlenty · · Score: 2, Funny

      The code is important. The braces are syntactical sugar.

      Guido van Rossum is that really you?

    66. Re:braces by Haeleth · · Score: 1

      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

      Wait, hold it right there. 80 column lines made sense back in the days when you were punching code into 80-column cards. Welcome to the 21st century, where things have changed slightly.

      I have dual 24" widescreens: under what conceivable circumstances does it make sense for me to restrict my code to 80 columns? It's not like any of my colleagues are using character terminals. Some of them have even more screen space than I do.

      You then can't clearly distinguish between the start of a block and a wrapped line without clearly inspecting the indenting.

      Maybe you should get a better editor. Mine certainly makes it easy enough to tell when a line is wrapping.

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

    68. Re:braces by DrugCheese · · Score: 1

      Well I use vi to code a lot and even it matches up braces for me (shift+5) but any decent ide will match them visually for you.

      --
      *DrugCheese rants*
    69. Re:braces by __aapbzv4610 · · Score: 1

      that's fine for single instruction blocks, but when each condition requires multiple statements, you really can't use that.

    70. Re:braces by laejoh · · Score: 0

      Ah! A python programmer!

    71. Re:braces by Jeremy+Erwin · · Score: 1

      How many coding windows do you regularly fit on on the screen?

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

    73. Re:braces by Anonymous Coward · · Score: 0

      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

      Never had to ssh in from halfway across the world over a low-bandwidth, high-latency connection, have you?

    74. Re:braces by biz0r · · Score: 1

      ok seriously...get back to reality. You speak as if solely for the fact its an interpreted language we need not worry about efficiency.

      First and foremost, MOST companies do not have unlimited resources with which they wish to spend on gobs of hardware. My guess, given your previous statement, that either you work for one of those very few companies that do, OR you have never ever had to scale a project (my guess is the latter).

      Secondly, templating engines more or less are generally useless. Why? Because when you are talking about properly written software the main goal is separation of presentation and business logic...which is very simple and much faster in execution without using a templating engine. You can still have easily manageable and readable code while using native constructs. Oh and also, for those one-off cases where you need some more complicated logic structures you don't need to resort to adding functionality to the templating engine or doing things in a funky way to get it to work.

      I am sorry, but templating engines built on templating engines are useless.

      --
      /* sig */
    75. Re:braces by Haeleth · · Score: 1

      Who said anything about needing to have the whitespace indicate that? We're talking about personal taste, not necessity.

      sizeof is a different case entirely, since it behaves like a function. if does not behave like a function -- you can't write foo(if(bar), if(baz));, while you certainly can write foo(sizeof(bar), sizeof(baz));. It's nice to preserve that distinction.

      The syntax highlighting, presence of braces and presence of an extra level of indentation on the next line don't cover it?

      What syntax highlighting, presence of braces, and presence of extra level of indentation? You may not have any of those. Better to request that coders include all possible distinguishing factors -- that way, if some idiot writes bad code like the following hideous example, you're still in with a chance of understanding it:

      white(bar(x--));
      while (bar(x--));
      whale(bar(x--));

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

    77. Re:braces by Dirtside · · Score: 1

      Um, real coders can read all of the common brace styles equally fast without a problem.

      --
      "Destroy science and religion. Science would re-emerge exactly the same; but not religion." - Penn Jillette, paraphrased
    78. Re:braces by Anonymous Coward · · Score: 1, Funny

      Imperative programming assholes! There should no "flow" in programs.

    79. 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. ^_^

    80. 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
    81. Re:braces by Hatta · · Score: 1

      When you hit enter after statement1;, does your editor put the cursor directly under the 's' or do you have to space over to it? My editor (vim) would put the cursor under the {. Keeping the first line of the block on its own line, lets my editor start new lines directly under it.

      --
      Give me Classic Slashdot or give me death!
    82. 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.

    83. Re:braces by dkf · · Score: 1

      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.

      I prefer to put braces on the same line as the thing guarding them (if, for, while, etc.) and that works very nicely; I only have a "naked" brace when at the start of a function or for a bare block (occasionally useful). It's also like the style required by some other programming languages. But the point about lines being cheap is a good one. In particular, only ever put one statement per line since that makes debugging much easier. (Yeah, theoretically they could do sub-line error locating, but they don't.)

      The other advantage with not putting on their own is that then you can see more lines on your screen at once. I like to have many things in view at once, and I've grown out of using 6pt fonts these days!

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    84. Re:braces by Nerdfest · · Score: 1

      Overall, the implementation of style standards these days is of waning relevance. With the advent of IDEs (NetBeans, Eclipse, etc) that will format the code to any style you like, it's not as important anymore. It only really matters when you check it in.

    85. Re:braces by Nerdfest · · Score: 1

      It actually takes twice as much space, but as I mentioned in another comment, you can use an IDE that will format code the way _you_ like. The entire team no longer needs to use the same style.

      Hopefully this can be one religious war that will actually end.

    86. Re:braces by Tony+Hoyle · · Score: 1

      Gross. That's an awful mixture of styles, and severely reduces readablilty (because your eye has to stop as your brain goes 'WTF?').

      Either use braces on the same line or give them their own lines. Don't mix styles.

    87. Re:braces by GreyWolf3000 · · Score: 1

      I disagree with this; I like to see the whole function in one screen. Code that adds two extra lines for every if/else block tends to take up too much screen space, and I have to start scrolling up and down while I'm reading/comprehending the function. I'm a proponent of 'if() {' and '} else {' for precisely that reason.. I indent properly, so the indentation lets me know when I enter a block (just like python). I have never had a problem reading code this way and I don't know of anyone personally who has had a problem with this.

      --
      Slashdot: Where people pretend to be twice as smart as they really are by behaving like children.
    88. Re:braces by dkf · · Score: 1

      Remember in C the {} does mean "create a new stack frame" as well as grouping.

      Strictly no. It's a context, not a stack frame (since you can see the outer variables despite those not having file or global scope). What braces do is give you a lifetime for some variables, as well as a sequence of statements for which those variables are in scope for. In C, that's just a (good) convenience. In C++ it closely affects RAII lifetimes, and so is very important. (Alas, it's not always compiled as efficiently by C compilers as it perhaps ought to be, but that's a whole 'nother story.)

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    89. 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.
    90. Re:braces by Tony+Hoyle · · Score: 1

      Not even then. It only really matters when someone else has to read it.

      As long as any reasonably competent programer can read it who gives a flying fig where the braces are? My one rule would be don't mix styles in the same source file (that gets ugly).

    91. Re:braces by Anonymous Coward · · Score: 0

      ..and Python developers are the diabetics of the industry.

    92. Re:braces by Anonymous Coward · · Score: 0

      I think people should choose whatever brace style they like, people should start making coding guidelines that actually matter like,

      - not putting a value in a variable until the very last moment
      - (related) don't use globals!!!
      - don't make functions that have side-effects, or document them very well
      - if a function has more than 20 lines you have to split it
      - use the framework, don't invent your own
      - ...

      but most importantly

      - write clear code, if using stuff like continue helps for that, use it

      Sorry, just my rant against nagging about stupid stuff like brace placement, using tabs or spaces, or empty lines. There's always tools like lint that can format the code any way you like. In fact all editors should lint the code automatically and then people could get on and discuss about the stuff that matters.

    93. Re:braces by stoicfaux · · Score: 1

      Who the hell holds a ruler up to the monitor? We're in the digital age. The ruler reference tells me that your mind is still stuck in the pen and paper age, which limits your ability to use and think about digital tools.

      For example, you could use a better editor. In vi, you can hit the % key to jump to a matching curly brace or parenthesis. Even easier would be: whenever you create the opening curly brace, you immediately create the the closing curly brace! Due to the miracle of digital editors you can then easily go back and insert code between the properly balanced braces!

    94. Re:braces by hpoul · · Score: 1

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

      if (condition)
      { statement1;

        statement2;
      }

      we actually learned that style in school (for C.. err.. ~7 years ago (?)) .. but i've never used it since i've moved to perl/java/.. (although i have no readability problems with any of those styles since IDEs show matching brackets anyway)

      --
      Find me at http://herbert.poul.at
    95. Re:braces by digitig · · Score: 1

      I've always found this to be clearer.

      Drawing a line up to an opening brace

      The clearest way is whatever way you learned first when you were learning to code. It's impossible to get programmers to agree to which is best, so you either need a diktat from above or evryone run the code through a prettyprinter (configured to the particular user) on the check-out process, so it's always formatted the way the person reading it likes.

      --
      Quidnam Latine loqui modo coepi?
    96. Re:braces by Anonymous Coward · · Score: 0

      Basically you are just discussing perfectly valid layout standards:
      BSD Style:
      if (something)
      {
          DoWork();
      }
      else
      {
          DoOtherWork();
      }

      and K&R:
      if (somthing) {
          DoWork();
      } else {
          DoOtherWork();
      }

    97. Re:braces by Anonymous Coward · · Score: 1, Insightful

      OverflowCount is equally unreadable to xyz124c, you insensitive Micro$oft/Java clod. Use overflow_count instead.

    98. Re:braces by jlowery · · Score: 1


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

      I prefer this coding style:

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


      I mean,
      you don't write an
      English sentence like
      this
            (
                  do you?
            ).

      --
      If you post it, they will read.
    99. Re:braces by Anonymous Coward · · Score: 0

      Completely agree, it makes for much clearer code.

    100. Re:braces by thogard · · Score: 1

      Older compilers (and many current 8 bit) will generate a new stack frame for most nested levles of { where they couldn't tell if there was a new frame or not. Modern compilers see a much larger picture.

    101. Re:braces by Foofoobar · · Score: 1

      Many people prefer this as it is easier to read just from a glance. By keeping the else with the brackets, you are keeping the indented statements separate from their containing loop. Far more readable when you have to deal with alot of code.

      --
      This is my sig. There are many like it but this one is mine.
    102. Re:braces by Anonymous Coward · · Score: 0

      GNU style->
      if(something)
              {
              do_something();
              }
      else
              {
              do_something_else();
              }

    103. Re:braces by thogard · · Score: 1

      You don't know how wrong that is...

    104. Re:braces by orangepeel · · Score: 1

      Exactly! That's why at the company I work for we don't indent with spaces or tabs. We indent with Wingdings.

      --
      Whoever designed level 61 in Frozen Bubble is a sadistic bastard.
    105. Re:braces by BrentH · · Score: 0

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

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

    107. Re:braces by Anonymous Coward · · Score: 0

      The problem with many programmers today is they are lazy and have your mentality of "just throw more hardware at it". I prefer to write highly optimised and efficient code that does a lot more with a lot less. If you have to throw more hardware at your software, then you suck as a programmer.

    108. Re:braces by peter+hoffman · · Score: 1

      Thanks for a reason for the second style which I find the most awful of the common ones (the first is the best). The second style makes my skin crawl and I never could see a reason that anyone who isn't flat insane would use it.

      I think, for most people, the reason styles which put braces at the start of lines are popular is because their editor doesn't support bouncing back and forth between braces (I don't mean matching highlighting, I mean a vi-style bounce).

      Another reason is that people aren't using enough width in their indentation and are using too many levels of indentation just because since they can.

      Finally, I think if you have several screens code inside braces that is a hint that maybe it ought to be a encapsulated as a function. Of course, I'm from the old school where individual files of code ought not to have more than a few screens of lines anyway....

    109. Re:braces by TheRaven64 · · Score: 1

      My laptop has a 15" screen. Openning vim, I see that this equates to 57 lines in a terminal. If your function is more than 57 lines long, even with every brace on its own line, then I would suggest that your function is too long. A function should, ideally, represent a verb in your program. If you have verbs that need definitions more than a page long then your language is not likely to be usable.

      --
      I am TheRaven on Soylent News
    110. Re:braces by Nyangau · · Score: 1


      if ( condition )
              TRUE-PART
      else
              FALSE-PART

      IMHO should be favored, as it is the TRUE-PART and/or FALSE-PART which know whether they are complex enough to require multiple statements, and thus a { block }, not the if ( condition ), which does not care.

      eg: TRUE-PART may be either

             
              statement1;
             

      or

             
              {
              statement1;
              statement2;
              }
             

      Aligning the braces like so


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

      IMHO should be discouraged, as it suggests that they are a part of the syntax of the if, which they are not.

      This generalises to if, for, while, do, functions, ...

      I read a book once which better explained this. It showed a progressive style of code development, in which nested statements were shown as indented solid black blocks, later filled in by code within the block.

      This style of indentation also works best when using line based folding editors, eg:


      if ( condition )
              x.. TRUE-PART
      else
              x.. FALSE-PART

      (Note: x.. should read ..., but if I type this, the formatting messes up).

    111. Re:braces by Anonymous Coward · · Score: 0

      Any good editor can treat a certain number of spaces as a tab. The tab argument is pretty weak.

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

    113. Re:braces by Anonymous Coward · · Score: 0

      As long as the actual engine of the web application isn't coded into the JSP/PHP pages, it's perfectly fine to use Java and PHP within the page for presentation reasons - to be frank that's the entire point of having these technologies.

      It's not just if-else, it's loops and other stuff. It's just coding algorithmically the presentation of a set of data that the engine has passed to the JSP/PHP. It's just one front-end to the engine, others could be native apps, web services, and so on.

      Having seen the alternative - servlets that embed HTML generation into the Java code ... yeah, just don't go there!

      Other JSP coding standards? Put as much of the code at the top of the page, which should hopefully just be stuff getting data out of the session and request maps, and some simple logic relating to presentation of said data. For loops, do the same within the loop body. Try and keep indentation logical within the Java portions of the code.

    114. Re:braces by canadian_right · · Score: 1

      At last, some sense. I use this style as I find it the most readable, easiest to line up blocks, and easiest to come back to in a year and figure out the code.

      if ( stuff ) // note space after/ before ()

      x=foo(a, b, c); // no spaces for functions

      --
      Anarchists never rule
    115. Re:braces by TedRiot · · Score: 1

      That's why when I did php coding we used to do it:

      include "header.inc";
      if ( $something ) {
          include "morehtml.inc";
      } else {
          include "someotherhtml.inc";
      }
      include "footer.inc";

      This made it nice enough for coders to worry about the logic, the HTML-guys worry about the presentation and we could even reuse the html-bits elsewhere in the site when needed.

    116. Re:braces by mrjohnson · · Score: 1

      Huh? You can take my code and the closing brace will always line up with the conditional statement. That's what people want to see anyhow, nobody cares about the brace.

    117. Re:braces by Blakey+Rat · · Score: 1

      I learned C on good ol' Mac OS 7. All the textbooks and guides there were in very verbose (possibly PASCAL-based) format:

      if( IAtePancakes)
      {
          DoSomeStuff();
      }
      else
      {
          GoEatPancakes( RIGHTNOW );
      }

      It's nailed into my brain so that I write almost all my code that way now, even JS. Everyone else hates it, says there's too much whitespsce.

    118. Re:braces by canadian_right · · Score: 1

      That is inconsistent and hard to read. It is much more important to see the structure of the if / else / for / while of the code than to save white space.

      If you have to maintain code that you haven't looked at for a year or more then having a very clear code indentation style makes seeing the code structure much easier. I've been using a style that you think 'wastes space' since an 80 column mda monitor was top of the line. The trade off for readability vs space was still no contest in favour of readability.

      I want to be able to do a fan-fold print out and lay a ruler down and see the blocks all line up with that ruler.

      --
      Anarchists never rule
    119. Re:braces by Anonymous Coward · · Score: 0

      YEAH... I was at least 5 when I started copying ColorBASIC programs out of rainbow magazine into my Tandy CoCo 2. ;)

    120. Re:braces by markkezner · · Score: 1

      I had the same reaction. Care to explain why it's wrong?

      --
      Dangerous, sexy, turing complete: Femme Bots
    121. 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?

    122. Re:braces by BotnetZombie · · Score: 1

      I personally prefer matching braces in their own lines, but when working with others it's not always a feasible option. IME, the most effective way to battle obfuscated code structure is to not write it that way (duh). Keep your methods short - less than one screenfill, have few indentations - no deeply nested if/else logic, and don't do many things in each loop. When you see your code deviating from that, it's usually a clear sign that it should be refactored.

    123. Re:braces by ultranova · · Score: 1

      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.

      But you can only do that if they both fit on the screen at the same time. And they won't if you insert gratuitous line breaks everywhere.

      Besides, I've always found it more logical that the first command of the if statement begin from the very next line. Empty or nearly empty lines are for grouping things within a block.

      Everybody else gets fired.

      You do realize that you could simply use an auto-formatting IDE ?

      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.

      And the time wasted scrolling back and worth because you can't see the whole block at once, how expensive is that ?

      --

      Forget magic. Any technology distinguishable from divine power is insufficiently advanced.

    124. Re:braces by CFBMoo1 · · Score: 1

      I do the same thing. I find it's 10xs easier for me to read and process code looking like that then when things are bunched up or without braces. It defines the local block for me when a condition is met. Like a visual cue and it's easier on my eyes.

      --
      ~~ Behold the flying cow with a rail gun! ~~
    125. Re:braces by Anonymous Coward · · Score: 0

      You don't seem to understand indentation of code. If you can't understand code blocks both with braces on their own lines, and with the so-called "obfuscated" other method, you probably shouldn't be coding with anyone but yourself.

      The compiler turns it into the same thing in the end.

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

    127. Re:braces by Anonymous Coward · · Score: 0

      And if you want to be made pure again, use ovrflw_cnt.

    128. Re:braces by Joebert · · Score: 1

      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.

      Which goes right out the window when things like XCache & Memcached get involved.

      Now it's like reading a newspaper where the editor decided to randomly switch between English, Spanish, & Klingon when trying to do anything with it for no reason.

      Some people argue that the potential "headers already sent" errors from inline PHP are reason enough not to do it like that because it makes it harder to bail, realisticly you should be checking if you should bail before the DOCTYPE is passed through though, so I really don't follow that gripe.

      --
      Wanna fight ? Bend over, stick your head up your ass, and fight for air.
    129. Re:braces by Anonymous Coward · · Score: 0

      sort of like this you mean?

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

    130. Re:braces by Visual77 · · Score: 1

      PHP is not ideal for doing presentation, no matter how you spin it. Try toying around with PHP's XSLTProcessor object. You use the PHP to analyze the environment variables, such as page request, get data, post data, session data and cookie data, and then use SQL to build an XML tree with the data needed for display. That XML tree is then parsed through an XSL template to generate HTML. This leaves absolutely no ending PHP tags in your PHP, and if done properly, you have no derivative data in your XML tree (for instance, a list of all users along with a count of how many users joined in the past month, that is just derived from the list and their join date), and the XSL generates all of the HTML. It's also far easier to look at this way, since the PHP documents all are pure PHP and the XSL documents are all pure DOM structure, alternating between HTML nodes and XSL nodes.

    131. Re:braces by maxume · · Score: 1

      You might as well have said "language evangelist" there, there is nothing particularly unique about python evangelists. I get the sense that there is satisfaction in having other people confirm their choice of language, rather than satisfaction in using a tool that works well for them.

      --
      Nerd rage is the funniest rage.
    132. Re:braces by Anonymous Coward · · Score: 0

      Wow! Two of the worst sins of all in the same block of code:

      - Indenting the braces to the same level as the code they surround is EVIL INCARNATE.
      - "if" is a keyword, not a function, so it deserves whitespace:

          "if (blah)", never "if(blah)"

    133. Re:braces by Anonymous Coward · · Score: 0

      or this perhaps:

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

    134. Re:braces by Anonymous Coward · · Score: 0

      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.
       
      You are kidding, right? No one reads one character at a time (except those with reading disabilities). We read in chunks, and it's easy to recognize that '} else {' means there is more to the if statement. Putting it on a seperate line makes it seem like a different thought, like a new paragraph does.
       
      Steve McConnell's Code Complete has a good section on formatting and readability, I sugest that everyone should read it (and the rest of the book).

    135. Re:braces by luis_schultz · · Score: 1

      Nor do I!

      Putting the braces in a new line has just the effect you mentioned. It destroys the purpose of blank lines. And the flow implied by the condition in an if, for instance, gets far from the condition itself.

      But really, the worst code standard ever is GNU's. Not only do they put the braces in separate lines, they have tadwidth = 2 and they write like

      if (condition)
          {
              foo
          }
      else
          {
              bar
          }

      Awful.

      BTW, I like GNU.

    136. Re:braces by thetoadwarrior · · Score: 1

      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.

      My guess is that they're grateful to get away from a company that uses a ruler to check code.

      It implies you're a bunch of code nazis and probably have to be because your code is too complicated or just plain shit.

    137. Re:braces by Anonymous Coward · · Score: 0

      This is wrong. A stack frame introduces a fair amount of overhead at the instruction set level. Creating a new stack frame for each block would be unacceptable because some inner loops will be critical to the overall performance of the code.

    138. Re:braces by Anonymous Coward · · Score: 0

      The whole "opening brace on the same line" bullshit was done by printers. Quite a few dumb conventions came about when code was sent to printers and they got to it.

      On paper, placing the brace on the same line looks better. It has to do with page flow or something. I don't really get it, but apparently printers think that a single line with a single character looks bad.

      Then why is the closing brace allowed its own line? I don't know. Never said it was consistent.

    139. Re:braces by mrogers · · Score: 1

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

      I don't know why, but I can hear my mother saying, "And if all the other programmers jumped off a cliff, would you jump off it too?"

    140. Re:braces by mrogers · · Score: 1

      You use indentation to identify program structure? What are you, some kind of human?

    141. Re:braces by magus_melchior · · Score: 1

      And, since this is really a matter of personal preference (I for one prefer the style that OP dislikes), it's a trivial matter to write a script to convert from one style to another.

      Of course, if the developers are forced to only use the code in the source tree (no local copies), converting the code every checkin and checkout would be a pain in the ass.

      --
      "We are Microsoft. You shall be assimilated. Competition is futile."
    142. Re:braces by Kz · · Score: 1

      Lines are cheap.

      lines are the single most expensive resource in computing, and it's getting worse.

      in the last few years, how has your HD space multiplied? CPU power? bandwidth? and how much more lines in your display now than 5 years ago?

      display space is the only thing in computing that's not in an exponential curve.

      (yes, programming ability also rises exponentially, for the good programmers, at least)

      --
      -Kz-
    143. Re:braces by Engineer42 · · Score: 1

      And I can't stand seeing them separated as it hurts the readability of the code :-)
      For me, wasting 3 lines of my viewing space for a simple 'else' is close a crime.

      This is actually not a good example of stuff to put in a set of coding guidelines. Any decent editor or beautification tool can correct the indentation or other visual issues automatically if you so wishes.
      I also don't think there are many programmers who would be confused and make mistakes because of braces/else put separately or on each their lines. If there are, they shouldn't be let near code :-p

      Also, this is one of the 'religious' coding issues where you're bound to run into other people's opinion. Making guidelines for unimportant stuff as this really is makes it much harder to setup guidelines for the important stuff.
      For how things 'look', it is often enough to specify that code should easily readable with blocks properly indented, no tabs (another religious issue, but by now mostly won by the no-tabs believers), consistency throughout a file, separation of functional blocks by empty lines, and braces around all blocks (even oneline if's).

      What is much more important in coding guidelines is to define coding behavior you don't want in your codebase. The obvious example being goto's/jumps.
      Another one I always like to have in for C/C++ is a section about how we do memory allocation. As pointers are the cause of at least 50% (imho) of all problems you encounter in C/C++, restricting how people use malloc/free and their resulting pieces of memory is very worthwhile.

      Also important is to limit your coding guidelines to what you are willing to enforce!
      Enforcing coding guidelines takes time, and sometimes your management will force you to skip reviews to ship in time. If you are not given time to revisit the code afterwards to enforce the guidelines, your code will start to have non-enforced parts in them, and this confuses people and worse, makes them use their own style and not the guidelines.
      In these cases, it is quite often better to have a smaller set of core guidelines aimed at eliminating dangerous coding practices than a big all-encompassing perfect set.

    144. Re:braces by Anonymous Coward · · Score: 0

      No, no, no! In Python this would be

      if condition:
                statement1
      else
                statement2

      Just the bare structure. in C it should be the same, just a little bit nicer, like this

      if condition {
                statement1
      } else {
                statement2
      }

      with the added grace of a brace to end the indent and stress that you are back to normal business.
      In the days when screens had 24 lines, this would also make code more readable.

    145. Re:braces by zermous · · Score: 1

      I rather believe the opposite. I prefer everyone to use their own style, as long as it is pretty in its own way, so that each piece of code has its own personality. I can tell at a glance who was working on the code and how careful they were being. I simply don't see why there is any value to all the code being consistent.

      When I fix someone else's code, I preserve their formatting style. It isnt pretty to switch styles in the middle of a bunch of code. But when I take 'ownership' of it, the first thing I do is reformat it to be my own pretty style. That clearly marks my turf.

    146. Re:braces by Kz · · Score: 1

      I only have a "naked" brace when at the start of a function or for a bare block (occasionally useful).

      i used to do like that: naked braces only at start of functions; but after learning several other more dynamic languages, now i prefer to put the brace in the same line as the signature:

      int funct(int a,int b) { ... whatever...
      }

      i guess this shift in taste comes from learning a few more dynamic languages, where functional programming is the norm, rather than the exception.

      --
      -Kz-
    147. Re:braces by Anonymous Coward · · Score: 0

      Incorrect. Braces are nothing, and don't deserve their own line. Tabs are what are important, and the only braces that get their own lines are those that have nothing following. As so:
      do{
          statements
      } while(condition);

      if(condition){
          statements
      }else one_statement

      switch(var){
          cases
      }

      notice 'statements' was plural. no braces for single line. You don't use a ruler to line up braces, you use a ruler to line up indents. Want to waste space? Waste someone else's space.

    148. Re:braces by Anonymous Coward · · Score: 0

      Who the hell holds a ruler up to the monitor? We're in the digital age. The ruler reference tells me that your mind is still stuck in the pen and paper age, which limits your ability to use and think about digital tools.

      Some of us hold our penis up to the monitor.

    149. Re:braces by Javagator · · Score: 1

      When you hit enter after statement1;, does your editor put the cursor directly under the 's'

      My editor is Emacs, and yes it does. I also have a number of custom c-mode settings in my .emacs file, so that probably helps, also.

    150. Re:braces by Kz · · Score: 1

      It's just a matter of what language you're used to in the first place; then you try to make other languages look like that one.

      that's a terrible advice!

      as they say, "you can write FORTRAN in any language" and that means you'll always be limited by what FORTRAN can do.

      when you learn a new language/library/framework/etc (and that should be every few weeks at least), use what is considered good style by experienced users. remember that you're a noob again! (and again, and again...)

      --
      -Kz-
    151. Re:braces by Anonymous Coward · · Score: 0

      You should probably step away from the keyboard, before a coworker who has to read your code kills himself.

    152. Re:braces by Vexorian · · Score: 1

      You know, I like python and all which is a recent shift from previous years... But I still don't like the implementation, syntactically important whitespace is one thing, but the lack of a visible limitator makes python code a little confusing when seeing only portions of it, I am never sure if an if/while/for/def block has ended.

      if condition:
          a=b
          c=d
          h=i
      (End of Page).
      oops?

      Anyway, something that for some reason isn't used in the C-like stuff.

      if (condition)
          a=b,
          c=b,
          d=9;
      else
          k=i;

      As I just noticed recently, if you can't join the statements with a , then the if's contents should have been on another function anyway...

      --

      Copyright infringement is "piracy" in the same way DRM is "consumer rape"
    153. Re:braces by heffrey · · Score: 1

      I think your problems are all laid out here. Ownership should be collective. If you have "your own turf", then your team has big problems.

    154. Re:braces by NMerriam · · Score: 1

      There are sound reasons beyond screen space for breaking long lines.

      Why isn't the editor automatically (optionally) wrapping lines to your window size, while also maintaining the proper indentation of that wrapped line? Any decent editor should allow you to set it to wrap at an arbitrary column number regardless of windows size, as well.

      Putting line breaks into text for anything other than signaling the end of a paragraph/statement is very 1980s.

      --
      Recursive: Adj. See Recursive.
    155. Re:braces by StormReaver · · Score: 1

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

      I started out indenting according to the formatting sadists we call K&R. After a few months, reading my code became very difficult for me since there was no obvious geometry to the formatting. I also used spaces for indentation, which became extremely cumbersome. To make it even worse, I used only two spaces for indentation. It was the worst of all possible styles.

      I read the Linux coding standards guide, where Linus dismissed two-character indentation as insane. He recommended 8-character indentation, which I thought was a total waste of space. I eventually tried it, though, I realized that it made reading code much easier. He still recommended K&R styling, but nobody's at the top of their game all the time.

      After a couple years of trying various styles I encountered on the 'Net, the one you mentioned is the one that solved all of the styling problems that had given me such headaches over the years. The geometry of the layout is easy to find and follow, 8-character tabs are easy for my tired eyes to focus on after long programming sessions, and the extra whitespace around code makes differentiating the various logic structures much, much easier than any other form I've seen.

    156. Re:braces by CockMonster · · Score: 1

      In C/C++/Java braces are a statement in themselves, they're a statement that contains other statements and define scope.

    157. Re:braces by talexb · · Score: 1

      Exactly. Follow the bottom brace up to the top will get you to a keyword: while, if, for. In vim, the % will bounce you between matching braces anyways. No idea what four fingered combination is the equivalent command in emacs. ;)

      And I'm quite fine with cuddled elses -- I'd rather see

          } else {

      on a single line than

          }
          else
          {

      over three lines. The more code you can read at once, the better. However, I do make a point to leave white space *after* an if condition. The code has to be readable -- that's number one.

    158. Re:braces by speedtux · · Score: 1

      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,

      Funny... the people who invented the language aren't doing that, and neither are most coding conventions.

      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.

      Maybe you should invest in better development tools than a ruler and a piece of paper.

      Everybody else gets fired.

      The people who should get fired are people who make a nuisance of themselves because they have stupid, unfounded ideas and try to impose them on others for no good reason. You know, people like you.

    159. Re:braces by KlaymenDK · · Score: 1

      Hi, I'm PyClippy. It looks as if you are trying to indent some code. Would you like to write code that does not need braces? [Y/N]

    160. Re:braces by Anonymous Coward · · Score: 0
      Ah, one of the "spaces are for wusses" types eh?

      I've used both same-line and next line braces at different companies, and I can understand the need for both.

      However I will never understand people who don't put spaces between keywords, brackets and braces. Did you grow up with C64 BASIC or something. Please, think of the spaces! Of course some people go overboard and put them between all punctuation characters, and that's equally annoying.

      // The foo is with us
      if (foo) {
      ....bar(foo);
      ....loney();
      }<br>
      // No foo, we are sad :(
      else {
      ....barbar();
      ....ella();
      }

      yeah, it's the inline comments that make me put else on the next line, rather than inline with the closing brace beforehand. I've only started doing this recently however. Coding styles change with age methinks. And let's not talk about trying to get Slashdot to actually print code samples nicely without using the "all comment is code formatted" option.

    161. Re:braces by Anonymous Coward · · Score: 0

      The real solution to this braces and indent problems is to change the editors and IDEs so that they can display and allow code to be entered according to the coder's preferences but store the code in a neutral form. Getting rid of a single, fixed format and replacing it with a wysiwyp (...is what you prefer) would eliminate this religious argument once and for all.

      This may require the inclusion of special tags to indicate the most basic format requirements (like keeping two or more distinct lines mutually aligned) and compilers changed to ignore these (or pre-compilers to strip the tags), but the cost and effort to get this widely accepted would be preferable to having people continue this interminable argument well into the next millennium.

      BTW - if you had a visual impairment, you would have a real reason for preferring one format over the other - I can't read some of the "standards" (such as K&R) easily regardless of someone's conviction that their preference is superior.

    162. Re:braces by CaptCovert · · Score: 1

      Some of us are still writing php on vim in a production environment.

    163. Re:braces by talexb · · Score: 1

      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.

      And exceeding the 80-column mark is plain WRONG. To have something hidden past the 80 column mark is dangerous. Don't do that.

    164. Re:braces by Anonymous Coward · · Score: 0

      Sounds like someone needs to use a better IDE :P

    165. Re:braces by Anonymous Coward · · Score: 0

      And what color should the bikeshed be?

      http://en.wikipedia.org/wiki/Bikeshed

    166. Re:braces by talexb · · Score: 1

      I would much rather see

          if ( Something ) {
              do something();
          } else {
              do something_else();
          }

      It's much clearer and easier to read.

    167. Re:braces by Nerdfest · · Score: 1

      Diffs between source code where the style has been altered will hide any functional changes. It makes it much easier if the style does not change between commits.

    168. Re:braces by BlaisePascal · · Score: 1

      I would find it hard to add a statement0 to that code.

    169. Re:braces by Anonymous Coward · · Score: 0

      For me, it's about visually scanning code. When you have code that has the start brace on the same line, you have to look all the way to the end of the line, and then all the way back to the beginning of the block.

      When it's on the next line, you simply look straight down the same column to see exactly where the block begins and ends.

      Again, for me, it makes code easier to read, especially if I didn't write it in the first place.

    170. Re:braces by gbjbaanb · · Score: 1

      amen. The one true rule is - never change coding styles.

      Even if you hate them, if you're presented with a chunk of code that put sthe braces in the 'wrong' position, it is your holy duty to keep them there and write any new code in the same style.

      That should be the only coding standard anyone needs; the rest are just arrogant posturings, usually written by people who don't bother to follow their own standards anyway.

    171. Re:braces by gbjbaanb · · Score: 1

      I think the point is that indentation is easier to understand from first glances than any syntactic statement delimiters. Once you start using indentation, bringing code together so its closer to the rest of the logical block makes it even easier to read.

      Something the rest of us should keep in mind even if we use non-K&R style, lots of vertical whitespace is bad, indentation is still good.

    172. Re:braces by Anonymous Coward · · Score: 0

      Unless, of course, you happen to live in the real world where money isn't unlimited, especially for small businesses or hobbyists.

    173. Re:braces by cyfer2000 · · Score: 1

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

      I guess you like Python very much.

      --
      There is a spark in every single flame bait point.
    174. Re:braces by Anonymous Coward · · Score: 0

      Beyond that, I put matching comments on the open and closing braces, indicating the purpose of the block. Not super useful in small methods, but very useful in larger ones. i.e. { // calculate the class average ... } // calculate the class average

    175. Re:braces by Anonymous Coward · · Score: 0

      ARGH! That style of bracketing and indentation reminds me of first semester computer science students in the computer lab. But to see it used in the professional workplace makes me want to slap the person upside the head.

    176. Re:braces by Anonymous Coward · · Score: 0

      What's really fun is when you have php that writes javascript that writes html.. yikes.

    177. Re:braces by GuldKalle · · Score: 1

      I actually find that it improves readability, because you can get syntax highlighting in both the php and html (and javascript if you want) parts of your script.
      It's a lot easier to read than echo("<html>") or equivalent.
      What's your approach?

      --
      What?
    178. Re:braces by Anonymous Coward · · Score: 0

      My boss has a quote for this.. "9 women can't have a baby in one month"

    179. Re:braces by xero314 · · Score: 1

      I wish I had mod points because this is the clearest form of using braces in code, but very few people use this form.

      I didn't believe this until I started using it, and now I can't stand looking at any other code.

    180. Re:braces by css-hack · · Score: 1
      By adding the following to your .vimrc, you can actually attain the effect you're looking for.

      " default text encoding (needed for the tab/trail chars)
      set encoding=utf-8

      " tab/trail chars
      set list listchars=tab:Y\ ,trail:Z

      The 'trail' character shows trailing spaces on a line, and the 'tab' characters represent tabs. Assuming you have set the width of your tabs thusly:

      " tab widths
      set ts=4

      Each tab character will be rendered as "Y{space}{space}{space}". Code like this is easy to interpret:

      Y _ Y _ function bob(int jim)
      Y _ Y _ {
      Y _ Y _ Y _ some_function_call();
      Y _ Y _ }

      Now, Y and Z aren't very good characters to use. I usually use unicode characters that I'll never use in my code--like the right-angle quotation mark for tabs, and the middle-dot for spaces--I just couldn't input them into this comment box.

      note: underscore characters were added to the above code to get the spacing right. evidently slashdot has no pre tag

    181. Re:braces by D-Cypell · · Score: 1, Insightful

      In my short experience in the workin' world...

      In which case, let me give you the benefit of my experience as well, the GP poster is absolutely correct.

      Its a funny thing, but *every* junior developer (which I define as 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.

    182. Re:braces by benhattman · · Score: 1

      HA! Try this on for size (actually witnessed in code)

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

    183. Re:braces by harry666t · · Score: 1

      Good point, sir. Actually, my opinion on the parens is not that they're evil or what, they have their purpose, they're an useful tool, may Gods bless them, but it's just the gazillion of different coding styles which have no use but to be a topic of endless arguments between hordes of blood-hungry programmers - that is my pain. In my view, Python is not trying to solve the problem of parentheses - there's no such thing as a problem with parentheses - it is trying to solve the problem with their users.

      Nothing is a problem until you make a problem of it.

    184. Re:braces by pablomme · · Score: 1

      It's just a matter of what language you're used to in the first place; then you try to make other languages look like that one.

      that's a terrible advice!

      I was being descriptive, not advisory. I was pointing out one reason why I (and potentially other people) prefer a given arrangement over another which doesn't exactly match the natural syntax of the language.

      For new language elements I obviously use non-Fortran syntax and arrangements, but for basic things like conditionals I tend to stick to my formatting habits.

      when you learn a new language/library/framework/etc (and that should be every few weeks at least)

      That sounds like an overstatement, but that might depend on what your job is. In my case, I certainly have better things to do than learn 15 programming languages a year. Like, actually use them to write something.

      --
      The state you are in while your HEAD is detached... - wait, what?
    185. Re:braces by Onyma · · Score: 1

      Scrolling up and down unnecessary pages of code attempting to decipher what is going on is even more expensive. Clean and formatted code is obviously is highly important but there is also a value in code density. Striking a balance is important and to me having 20 lines of lone { and }'s on the screen swings that balance too far into the 'useless' category. I don't compact code to any extreme but I do try to avoid generally "blank" one character lines inside connected constructs.

      "} else {" is not unreasonable to me at all. It keeps the construct together and if your eye has to scan to see something 2 characters away then you're sitting way too damn close to the screen :)

      --
      Play me online? Well you know that I'll beat you. If I ever meet you I'll "/sbin/shutdown -h now" you. -Weird Al, kinda.
    186. Re:braces by Anonymous Coward · · Score: 0

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

      Quality PHP frameworks, such as Drupal, use templates to separate the HTML from the PHP. Basically everything sent to the browser can be themed by creating the necessary template file, if it doesn't already exist, and overriding the module's template. Basically the exact opposite of what you suggest. The key is they then cache the output. Running just enough PHP to know that your cache is up-to-date is far less expensive (and more maintainable!) than the performance hack you propose.

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

    188. Re:braces by jabelli · · Score: 1

      Yeah, I stopped doing 80 columns a while ago, and switched to 120. 120 happens to line up perfectly on my monitor when VS is maximized.

      OTOH, using unlimited line length sucks. You either have an unreadable mess when the editor wraps the lines, or you have to scroll to the right to read everything. What we really need is an editor that can dynamically format the wrapped lines on the screen.

    189. Re:braces by Rene+S.+Hollan · · Score: 1

      There are two issues: code layout (style), and code/documentation/naming consistency (standards).

      There are a lot of different styles. What matters is that a consistent style is used for code that is checked in, and that that style be reasonably readable by all. Otherwise source code control system diffs become cumbersome. (Yes, one can diff on retrieval, but that gets expensive and not all source code control systems support it.) Beyond that, it would be really nice to reformat to whatever style the individual is accustomed when one spends a lot of time with the code).

      My personal irritants are styles which are inconsistant. For example, indenting function argument lists right beyond the left bracket, but not aligning a right bracket and statements or intra-struct/class declarations the same way, It's not done in the latter case because it is "space wasteful". Is it not space-wasteful in the function call case as well?


      if (foo) {
            blah
            blah
      }

      then why not

      void fooFunction( ...arg, ...arg
      )

      ?

      Personally, I like my bracketing constructs to line up, brackets as well as braces. Furthernore, I find opening braces on a line by themselves wasteful. I don't object as much as I used to, but I come from the days of 24x80 text terminals, and seeing more code at once was a plus.

      SO,


      void fooFunc
        ( arg1,
            arg2
        )
        { stmt1;
            stmt2;
        }

      (Note the indent for the bracketing elements, and the additional indent for the items bracketed. I'm not pedantic about the former.)

      In practice, if anything within bracketing constructs fits on a single line, I'd collapse it to that. So,


      void fooFunc(arg1, arg2)
        { stmt1;
            stmt2;
        }

      Or, even:


      void fooFunc(arg1, arg2) { stmt1; stmt1; }

      That works great for little code snippets which are idiomatic, and extend to short switch cases with breaks.

      As for complex compound expressions that don't fit on one line, I break them up on the basis of multiplicative and additive operators, and compound variable references are broken on the basis of direct (.) and indirect (->) selection operators. The common rule is to break arbitarily with an extra indent. I place diadic selectors or operators in the indent margin of the second line, consistent with the precedence of the operation. So, turn the page sideways and you see the compiler parse tree -- which is what you really need in the case of a complex compound expression, particularly in an if statement. So,


      if
        ( (a < b)
            && (b < c)
        )
        { stmt1;

                  val1
              = a + b + c;
        }

      The assignment is really odd here, and I have played with


      val1
        = a + b + c;

      as well, but the former is consistent with my diadic rule, and th latter is an exception.

      --
      In Liberty, Rene
    190. Re:braces by Rene+S.+Hollan · · Score: 1

      Damn. There were extra spaces in places. I hope people get the idea.

      The bottom like is that, given a style standard, I should be able to take ANY valid piece of code and format it according to that style, correctly.

      --
      In Liberty, Rene
    191. Re:braces by istartedi · · Score: 1

      That's what I do. It seems like the burden of "low level visual processing" is lowest this way. When I look at the previous style, I find myself being just a bit annoyed and distracted by the if and else. Either way is vastly superior to K&R style. With that, I find I have to sit there and slow down, tediously parsing the code. Even worse is when people have a one-liner as an if statement, and don't use braces.

      --
      For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
    192. Re:braces by DiarmuidBourke · · Score: 1

      You know, I like python and all which is a recent shift from previous years... But I still don't like the implementation, syntactically important whitespace is one thing, but the lack of a visible limitator makes python code a little confusing when seeing only portions of it, I am never sure if an if/while/for/def block has ended.

      if condition:
          a=b
          c=d
          h=i
      (End of Page).
      oops?

      If you're reaching the end of the visible page inside your if block, then perhaps you should consider refactoring your code so that it fits on the page. Therefore allowing the function(s) name tell you what the code is doing. There's nothing wrong with it's implementation, just the programmer.

    193. Re:braces by Anonymous Coward · · Score: 0

      I find it ironic that your message was pretty much right on the money, but the presentation (sentence fragments, run ons, and lack of paragraph formatting) made it difficult to read. Sort of like digging through code written without regard to any coding standard! But I guess that makes me a grammar Nazi.

    194. Re:braces by Splab · · Score: 1

      Nice to see at least one sane person reads Slashdot :-)

      People have completely missed the point and most responds looks like they have around zero knowledge about what really matters.

      I've seen people spend hours to optimize something for 1-2% increased performance - its a waste of time if it doesn't increase performance by orders of magnitude. The price per cycle easily dwarfs the price of buying new hardware.

    195. Re:braces by UnderCoverPenguin · · Score: 1

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

      Conceptually, the braces are equivalent to "begin" and "end", so some people will look at:

      } else {

      and see:

      end else begin

      --
      Don't try to out wierd me, three-eyes. I get stranger things than you, free with my breakfast cereal. --Zaphod Beeblebr
    196. Re:braces by vaz01 · · Score: 1
      Those crazy long lines do seem to happen a lot in C, and C++ and Java too (new instance passed to new instance passed to new instance, maybe). Maybe it's just habit? It's not ever necessary, I don't think.

      I like taking any chunks of logic that are secondary to a function's algorithm and giving them their own function, even if I'm not currently using it more than once. Unless you're developing for a platform with limited memory or a profiler tells you a function it taking too long, there's no reason this could be a bad thing. It can really help make code more self-documenting if you use more and smaller functions with clear names... you can afford the space to write out a longer, clear name if you're moving secondary logic to functions of their own.

      Also, I'm a fan of splitting up long expressions (like in conditionals) over lots of lines and lining them in a nice way, it's clear and easy on the eyes. Same with a group of assignment statements at the start of a block, declaring a class's instance variables, etc.

    197. Re:braces by gadzook33 · · Score: 1

      Maybe it's a scheme for people who write brief, concise, elegant code.

    198. Re:braces by Anonymous Coward · · Score: 0

      "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" - by Glonoinha (587375) on Sunday July 20, @10:18AM (#24261963)

      Agreed, 110% - it's how I code (so, I am a bit biased), as it makes for EASIER debugging (such as between C/C++ open/close braces &/or Delphi begin-end statements/reserved words)...

      "Everybody else gets fired." - by Glonoinha (587375) on Sunday July 20, @10:18AM (#24261963)

      OH, I dunno about THAT, lol... everyone has "off days" or is in a hurry etc. @ times, & @ times? They just need to be shown "better things" (purely relative term) is all... whether they use them or not though? Up to they. There are times I have seen where the "low man on the totem pole" comes up with a GREAT IDEA @ times too:

      "Even a blind squirrel finds an acorn, @ least now & then!"

      See - I wouldn't go & say I am a 'real coder' (purely relative term, I figure @ least, because if it works? IT WORKS... right?)

      ---

      Then again - There is a matter of logical efficiency (& yes, readability/maintainability, + speed of operations too)

      Sometimes though, that comes later ONLY...

      ---

      Heck - I did so here recently, Early June this summer in fact!

      APK Hosts File Grinder 4.0++:

      http://www.thenewtech.com/forums/chit-chat/today-4378/index32.html#post16032

      It allows me to:

      ---

      EASY Integrate the HOSTS files of others, such as mvps.org, & others... even if in other internal line-by-line formats, into the MOST EFFICIENT format that is (0[space]IP Address), first, & then...

      Allows speed up access to your fav sites, via 1st pinging them, & adding them to the normalized non-repeat line items list on the right hand side of its screen.

      Allows Add/remove sites from a hosts file, but by first checking for their pre-existence inside the HOSTS file on ADDS, & rejecting if there already (& adding if NOT present)

      Lastly, it will FULLY NORMALIZE (accurately 110%) a HOSTS file (removal of duplicates)...leaving you with one in the MOST efficient format line-wise there is (consumes less memory & faster loadtime from disk) & fully alphabetized sorted.

      ---

      I documented it in the URL above, @ a forums during its build in fact, & that helped me think believe it or not...

      In doing so (rewrite or an earlier version that took DAYS of runtime, & is now down to 1-2 hours (over a massively unrealistic 1 million++ lines record entries HOSTS file test data set with repeats in it, for testing "normalization/repeats removal" (for ondisk & in memory efficiency of HOSTS file data + faster loadtime into RAM from disk, into the local DNS cache)?

      Hey - I was happy w/ the result, so far (couple hours a night or on weekends @ most)... maybe 1 week total time, tops.

      I achieved some "HUGE" gains in processing time efficiency + speed on a freeware I wrote years ago (but never released, it was poorly done, even in my opinion then 7 or so years ago, it worked, but SLOW in certain portions (normalizing a HOSTS file)), though I released others over time for others to use/enjoy, but ONLY when they were pretty fairly really well done (efficient enough, niceties for users, etc.).

      ---

      When I need a tool? I just write it up myself... this is the neat part of being able to write code, don't you all agree? Nothing like being your own builder of your own desktop's "electric furniture & appliances", lol!

      Want a job done right?? DO IT YOURSELF, & get EXACTLY what you want (much as how Harley bikers build their own bikes, OR, pc hardware folks building their own machines... which I figure, most coders do, anyhow too, for their OWN systems).

      APK

      P.S.=> Now, as to my self-assessment, on the "real coders" thing? Hey - IF you can get the j

    199. Re:braces by Bryan+Ischo · · Score: 1

      Oh you must be right, only you in your infinite wisdom can decide what is good practice and what is bullshit.

      Well for your information, my preferred mode of working is with two emacs buffers side-by-side. In this case, you can't fit much more than two 80 column buffers onto a modern computer screen. On my current screen, the best I would be able to do would be 97, and that's if I fill the whole screen with emacs, which I prefer not to do. So observing the 80 column rule helps me in my working environment.

      It's absolutely true that my particular preferred way of working is only one very tiny datapoint in deciding what number of columns to restrict code to. However, there has to be a limit, and someone will always bitch about it whatever it is. I have no problem making my code a bit more 'vertical' to make it fit 80 columns. I have never ever been unable to write readable 80 column code no matter what the situation. 80 columns is the historical limit, and I see no problem with it. Learn to code within the limit and you will be fine.

    200. Re:braces by paulatz · · Score: 1

      What's not to like? I want to have the double closing curly brace "}}", for the rest it depend on the length of for specifier.

      --
      this post contain no useful information, no need to mod it down
    201. Re:braces by kv9 · · Score: 1

      I agree, 80 chars line lengths are just as obsolete and oldfashioned like line breaks.

    202. Re:braces by kv9 · · Score: 1

      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.

      I'd venture a guess that you're a Visual Studio user. also, real coders hate redundant shit. redundant shit, oh like I don't know, using braces on top of indentation to find their way around code?

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

    204. Re:braces by Anonymous Coward · · Score: 0

      but python is fixed format - neither basic nor lisp are, afaik, fixed format languages.
      that is something which first annoyed me, but now see as a real benefit.
      discussions about where to open/close braces or indention style become obsolete and programs look quite similar. Except for other coding standard issues like naming.

    205. Re:braces by UnderCoverPenguin · · Score: 1

      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.

      1. Yes, "cuddled braces" can be hard to track.

      2. Even when braces are not cuddled, I still use the brace matching feature available in any decent code editor.

      --
      Don't try to out wierd me, three-eyes. I get stranger things than you, free with my breakfast cereal. --Zaphod Beeblebr
    206. Re:braces by kramulous · · Score: 1

      Gets my vote. Readability is clean. Enables quick scan debugging (with eyes that is).

      --
      .
    207. Re:braces by Anonymous Coward · · Score: 0

      it saves time when you are pulling blocks of code out while debugging

      if (condition1) {
          somework
      } else if (condition2) {
          somework
      } else {
          somework
      }

      now, to pull condition 2 out (one way) (and imagine that somework is more than a few lines)

      if (condition1) { ...
      }
      #if 0
      else if (condition2) { ...
      }
      #endif
      else { ..
      }

      vs:

      if (condition1)
      {
      }
      else if (condition2)
      {
      }
      else
      {
      }

      becomes

      if (condition1)
      {
      }
      #if 0
      else if (condition2)
      {
      }
      #endif
      else
      {
      }

      Just an example. I used to do my braces the first way, after a while of working the other way (debugging, refactoring, adding preprocessor decisions as to WHAT you should do in condition two, and whatever else I had to do to modify the code) I found this was better.

      But yes, my coworkers and I all work on 30inch Apple displays, so space isn't such a big deal ;)

      Just my $0.02

    208. Re:braces by vaz01 · · Score: 1

      Agreed. I don't think it ever looks good to have an opening and closing brace on the same line (especially since you don't need the braces at all, unless you have multiple statements in there, which would make it even worse to read). Especially since the first thing I thought when I looked at that was, did he close the else block on the same line as its last statement? Then I saw the closing brace below and starting looking for a nested (multi-line) block, and then noticed the unnecessarily {}'s on the one line.

      I think

      if(something) do_something();

      is just as good as (or better than)

      if(something)
        do_something();

      for simple one-line conditionals, especially for things like

      if(x > 0) return x;
       
      // or to get a bit Java-ish
      if(bad_thing) throw new BadThingException();

      but these are simple conditionals that are really clear in one line. If you're going to tack on any elses, be consistent in how you indent all the blocks, so

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

      I think this is a bit more than just personal preference, if you have a list of alternatives they should all be indented equally so they get equal attention.

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

      YOU FORTH LOVE IF HONK THEN

    210. Re:braces by Myopic · · Score: 1

      I did that on my first project in the CS intro class in college. I got a special note on my code saying that the grader had never, ever seen anything so atrocious as that style of indenting. I switched to a more common style in order to conform.

      And for the record, I don't understand the problem with using

      } else {

      The "if ... else" construct is like a compound sentence. The else goes on the same line as the end of the if, because it's a continuation of the same thought, like using a comma or semicolon when writing sentences. In other cases, it's more clear to split them out with a blank line, but I usually don't bother, and if someone put in needless blank lines all the time, that would be annoying.

    211. Re:braces by Seraphim_72 · · Score: 1

      At what point were we writing English? I thought we were writing logic. In any event there is a form to dissect English sentences into there proper forms. It looks nothing like English either. Your all on a line code is horrible to debug because only you know where to find the breaks. The equivalent in English is dropping all of the spaces, indents and CRLF.

      --
      Slashdot, where armchair scientists get shouted down and armchair theologians get modded up.
    212. Re:braces by Anonymous Coward · · Score: 0

      What's with all of these braces? Us snake-heads don't need any of that. We just use Tabs/Spaces!
      -Gp

    213. Re:braces by UnderCoverPenguin · · Score: 1

      >Here's a language with no braces:
      >
      > IF condition THEN
      > statement1
      > ELSE
      > statement2
      > ENDIF

      Shouldn't that be:

              IF condition
              THEN
                      statement1
              ELSE
                      statement2
              ENDIF ;)

      --
      Don't try to out wierd me, three-eyes. I get stranger things than you, free with my breakfast cereal. --Zaphod Beeblebr
    214. Re:braces by UnderCoverPenguin · · Score: 1

      >Here's a language with no braces:

              IF condition THEN
                      statement1
              ELSE
                      statement2
              ENDIF

      Shouldn't that be:

              IF condition
              THEN
                      statement1
              ELSE
                      statement2
              ENDIF

      --
      Don't try to out wierd me, three-eyes. I get stranger things than you, free with my breakfast cereal. --Zaphod Beeblebr
    215. Re:braces by Anonymous Coward · · Score: 0

      Nice fantasy, but there isnt enough time in the day for everyone to get equally up to speed on everyone else's code.

    216. Re:braces by Platinumrat · · Score: 1

      I'm with you on this. I would go as far as say that the Configuration Management system that you deploy should apply a style guide to every piece of code checked in and out (maybe with the option of users choosing their style on the out path). But Style is just fluff. The important thing content. Using C casts, uninitialised pointers, no design patterns === PROBABLY BAD CODE. I sympathise with the OP... I've been given a project to run that is trying to tie together three different code bases written over the last 5 years; each with their own coding standard. One even still dictates 80 characters per line. So I end up with a religious war every time I mention coding standard. Since it's mainly C/C++, I'll go with either HICPP or MISRA++ coding standard and enforce the Style at the CM tool. Just wait for the screams.

    217. Re:braces by vaz01 · · Score: 1

      Some compilers get a bit weird about what order they want to execute things in a comma-separated statement.  I think you're generally not supposed to assume things will happen in the order you wrote them, which kinda defeats the purpose of C being imperative programming.

      (I might be wrong, but I think I remember reading that.)

    218. Re:braces by Javagator · · Score: 1
      I would find it hard to add a statement0 to that code.

      I will believe "mildly inconvenient", but not "hard".

    219. Re:braces by MichaelSmith · · Score: 1

      Coding with eclipse and checkstyle is so structured these days that I question the benefit of having code at all. The source is being used as a database. Perhaps that is the way it will go.

    220. Re:braces by MichaelSmith · · Score: 1

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

      If you have worked in pascal or ada then it makes perfect sense.

    221. Re:braces by Jesus_666 · · Score: 1

      That's bound to be fun debugging.

      s/debugging/rewriting from scratch/. PHTML is usually about as readable and maintainable as code that emulates any kind of control structure through GOTO. Even less, probably.

      --
      USE HOT GRITS WITH STATUE OF NATALIE PORTMAN (NAKED AND PETRIFIED)
    222. Re:braces by MichaelSmith · · Score: 1

      There are sound reasons beyond screen space for breaking long lines.

      Why isn't the editor automatically (optionally) wrapping lines to your window size, while also maintaining the proper indentation of that wrapped line? Any decent editor should allow you to set it to wrap at an arbitrary column number regardless of windows size, as well.

      Putting line breaks into text for anything other than signaling the end of a paragraph/statement is very 1980s.

      If editors could put braces where the reader expects them to be we wouldn't be reading this whole discussion.

    223. Re:braces by Anonymous Coward · · Score: 0

      That's why I always have multi-line lines of code, I always indent the extra lines by 2 or 3 indents. That way they can't be confused with a standard indent for a block or something.

    224. Re:braces by IntlHarvester · · Score: 1

      The real solution to this braces and indent problems is to change the editors and IDEs so that they can display and allow code to be entered according to the coder's preferences but store the code in a neutral form.

      Pretty much every form of BASIC (up through VB6/VBA) did this by storing the code in a tokenized form.

      In the general case though, you would have to pry plain-old-text out of most programmers' cold dead fingers.

      --
      Business. Numbers. Money. People. Computer World.
    225. Re:braces by Fallingcow · · Score: 1

      I find that style very hard to follow if you've got a lot of conditionals in a row, like an if/elseif(x6)/else situation. I think it's because if I put my first curly on the same line as the if, then any single-character line is always the END of the bit of logic. Putting both on their own line makes it, at a glance, like taking the space out from between sentences and lower-casing the first letter.

      Only having the last one on its own line gives the character more meaning when quickly skimming, IMO.

    226. Re:braces by TLLOTS · · Score: 1

      You should really write those kinds of control statements as

      <?php if($something): ?>
      more html
      <?php else: ?>
      some other html
      <?php endif; ?>

      that way you avoid any confusion as to what the closing brace is for.

    227. Re:braces by Thiez · · Score: 1

      It's not all that bad. From memory (I'm sure the x86 asm below is fairly, but probably not 100%, accurate)

      push ebp
      mov ebp, esp
      sub esp, #amount

      > code in the block

      leave #amount

      While there is overhead, which is unacceptable when it can easily be involved, the overhead of these instructions is not that impressive when compared to a branch-misprediction.

    228. Re:braces by Anonymous Coward · · Score: 0

      I used to not like that, but after 10+ years of programming C++, I've found I like it now. The thing is that allows me to see more lines at the same time on the screen, and context is important when debugging or reviewing code.

      If the indentation is consistent, the braces in the same line do not bother me. A lot of empty vertical space does.

      I guess is something you grow into (or not..)

    229. Re:braces by Anonymous Coward · · Score: 0

      That has to be the most vile, horrific code "style" I've ever seen. It's not just bad, it's inconsistent, ugly, and hard to read. I'd be embarrassed to say it was my preferred "style" if I were you.

      PLEASE learn about code-style!!!

    230. Re:braces by freakxx · · Score: 1

      You can make it even more understandable by the following:

      if ( condition )
                {
                  statement1;
                }

      else{
                statement2;
              }

    231. Re:braces by MichaelSmith · · Score: 1

      Hopefully this can be one religious war that will actually end.

      Not likely.

    232. Re:braces by Ninja+Programmer · · Score: 1

      That's the most ridiculous thing I have ever heard of.

      Lines are *incredibly expensive*. Your screen cannot be expanded, the dot pitch cannot be improved, and your printer cannot ram 400 lines of text into a single sheet at a readable font.

      The number of ergonomically useful vertical lines is essentially fixed. You can spend as much money as you like and you cannot realistically increase this.

      Time is *NOT* wasted by brace hugging; more relevant lines of code can appear on the screen at once.

    233. Re:braces by elronxenu · · Score: 1

      If forth you love, honk you will.

    234. Re:braces by thogard · · Score: 1

      The world does have CPUs that aren't x86. For some of them, adding a stack frame is adding numbers to the constants you use relative to the stack pointer. When you have to build a virutal machine to run 16 or 32 bit code on an old 8 but CPU there are other tricks as well.

    235. Re:braces by SL+Baur · · Score: 1

      Yeah, I stopped doing 80 columns a while ago, and switched to 120. 120 happens to line up perfectly on my monitor when VS is maximized.

      If you are writing any kind of meaningful code, then you are not writing it for yourself to be able to read, but those who come after you. I do not know what VS means, but it sounds like something to avoid like the plague.

      Standards in line length will always be arbitrary. The reason why 80 columns was chosen was because it was pretty universal - everything displayed in 80 columns. Something that displays fine on your monitor (I once coded a program to 132 column width because I could get 132 column printouts) is dumb - I cursed myself out for stupidity when I had to debug it later on different equipment.

      Something that displays "correctly" in your environment will rarely display decently any where else. 80 columns is nice actually because you can usually get more than 2 editor windows side by side displaying in that width and lines longer than that suck for reading.

    236. Re:braces by SL+Baur · · Score: 1

      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.

      What is the difference between that, and matching indentation with the line with the opening brace? One less screen line.

      Everybody else gets fired.

      That's wanking and unprofessional.

    237. Re:braces by SL+Baur · · Score: 1

      Getting rid of a single, fixed format and replacing it with a wysiwyp (...is what you prefer) would eliminate this religious argument once and for all.

      Not even close. That does not solve the problem of reading diffs (stuff in patch(1) format).

    238. Re:braces by SL+Baur · · Score: 1

      Who the hell holds a ruler up to the monitor?

      I do, but then I'm working on maintaining a most unevenly coded system right now.

    239. Re:braces by SL+Baur · · Score: 1

      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.

      After they are gone, someone still has to clean up the mess. There is not always the luxury of rewriting a passably working program.

    240. Re:braces by n+dot+l · · Score: 1

      How do you do multi-line if statements, then? I usually type:


      if( some_dumb_library_function_that_takes_lots_of_params(
              param1, param2, param3, oh_em_gee_will_it_never_end,
              stop_the_pain_please, param6, param7, true, false, true, -1 /* -1 means "any" */,
              functions_with_this_many_params_should_be_a_compiler_error,
              create_temp_context( ctx ) ) == fourty_two )
      {
              lots_o_code();
      }

      Having the opening brace on its own line doesn't just show me where the conditional code starts, it also keeps conditions that have to be split over multiple lines from looking like they might be part of that code. I mean, yeah, I could create a temporary variable and assign the result of the long condition to it and then do an if on that, but I consider it even worse since it introduces extra, and unnecessary, variables into the scope (which should be a shooting offense, IMHO).

      The other issue I have with that is that with syntax highlighting you end up looking for opening text that's one of several colors (but not the comment color), which is harder for me to scan for than a line with a single brightly colored curly brace in it.

      To each their own, I guess. This is the style I use in my code. When hacking someone else's, I use their conventions.

    241. Re:braces by Anonymous Coward · · Score: 0

      Is your screen a mile high?
      No?
      Then the example you posted is a waste of screen estate.

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

      is more readable to me and doesnt have that copy&pasted together codesmell I often sniff in newbies code.

    242. Re:braces by jc42 · · Score: 1

      And exceeding the 80-column mark is plain WRONG. To have something hidden past the 80 column mark is dangerous. Don't do that.

      Actually, the code shouldn't go past column 72. Columns 73-80 are used for the sequence numbers, for when you accidentally drop the card deck and need to sort it. Everyone with any experience knows that.

      Youngsters these days with no experience; Jeez ....

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    243. Re:braces by Anonymous Coward · · Score: 0

      Not them, and that is a good enough reason.

      And that's one of the reasons why you aren't.

    244. Re:braces by duckInferno · · Score: 1

      Maybe, but I'm fairly sure nobody uses the English programming language.

      --
      Fool me once, shame on you. Fool me twice, watch it -- I'm huge!
    245. Re:braces by |/|/||| · · Score: 1
      Spaces always seem to end up making a mess. I like to use all tabs:

      [tab]function(arg1,
      [tab][tab][tab]arg2) {
      [tab][tab]//code
      [tab]}

      That makes it pretty clear that the "}" closes "function", and that "arg2){" is just a continuation of a long line.

      --
      [javac] 100 errors
    246. Re:braces by Anonymous Coward · · Score: 0

      good to see someone who does it like this too!

      works especially well for me since my if statements tend to run complicated, so having them on their own makes it easier for me to read later.

    247. Re:braces by vikstar · · Score: 1

      Code isn't important, what is important are the electrons which guide other electrons around in the circuitry... code is just syntactic sugar.

      --
      The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.
    248. Re:braces by vikstar · · Score: 1

      I'm sorry, but I like to think we've evolved our coding standards from when quipu were being used.

      --
      The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.
    249. Re:braces by vikstar · · Score: 1

      Lines are not cheap at all, they require you to scroll through code that isn't visible on the screen, or they required you to use valuable short term memory to remember code that should already be visible. If you can't figure out the "obfuscated" code then you're using the wrong font/size or you're line spacing is set incorrectly.

      --
      The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.
    250. Re:braces by Waccoon · · Score: 1

      Try using a template engine with built-in caching. Give it code and let it do the conversion for you. A smart engine knows how to get rid of the redundancy. Heck, if you're desperate, even a roll-your-own solution isn't that hard to make.

      Of course, as an avid PHP programmer, I've found there's not much out there that qualifies as "smart" in the PHP world.

    251. Re:braces by IBitOBear · · Score: 1

      I _only_ write code where the control delimiters (e.g. "{" and "}" or ";") are on the same line as the conditional (e.g. "if" "else" "do" "while" "switch" etc.

      That rule comes from the fact that I have used systems where line splitting and dropping is rife. (It's perhaps part of the old-unix-guy mentality.)

      Consider what happens if you drop the line containing "do" in a do-while construct. If you have the conditional and delimiter on the same line the code suddenly fails to compile.

      Since an anonymous block brace-statements-brace is a completely legal C/C++ construct without any conditionals etc, there is a chance for confusion when you separate the braces onto their own lines.

      Consider what happens if someone accidentally pastes/adds line after the else and before the opening brace. That's just plain induced and subsequently invisible error. It can always happen, but it isn't anywhere as likely when the braces are bound to their verbs.

      Insertion just before the else, if the else is on its own line, is just as dangerous. A line-paste of a random if conditional will become invisible inclusion. Not as common as the spurious delete, but possible.

      As a second issue, Writing "if-paren-space" as opposed to "if-space-paren-optional_space" is "wrong" for me because you make the "if" construct look like a function call, when it is instead a language construct.

      I have done coding in all sorts of standards and circumstances. The code you have above is "correct" to my eye except for the lack of a space after the if.

      You may not be able to "stand" seeing it, but it is superior (imho) to splitting it.

      The problem is that you have yet to internalize the continuity of the conditional and the grouping operator. you might as well complain that "b * -a;" should have a new-line before the -a because the two operators look wrong together. That is, putting new-lines in the middle of structurally bound elements is just wrong (unless it cannot be avoided of course, nothing is absolute... 8-)

      --
      Innocent people shouldn't be forced to pay for inferior software development.
      --"Code Complete" Microsoft Press
    252. Re:braces by shish · · Score: 1

      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

      Drawing a line from a close brace to an opening brace is useless, as the opening brace has no actual effect on code; drawing a line straight up to hit the opening statement (if, while, etc) is just as clear (actually, it's the indentation that makes things clear, not the braces), but far more useful.

      --
      I mod down anyone who says "I will be modded down for this", regardless of the rest of their comment
    253. Re:braces by shish · · Score: 1

      flowto is the new-age goto?

      --
      I mod down anyone who says "I will be modded down for this", regardless of the rest of their comment
    254. Re:braces by Ihlosi · · Score: 1
      Drawing a line from a close brace to an opening brace is useless, as the opening brace has no actual effect on code;

      Isn't the opening brace where creating stack frames and other miscellaneous clerical stuff takes place ?

    255. Re:braces by sean4u · · Score: 1
      It's like Brian said:

      You're all individuals

    256. Re:braces by sean4u · · Score: 1
      Someone stop me! I only said

      that indentation style was good enough for Jehovah

    257. Re:braces by Ihlosi · · Score: 1

      I _only_ write code where the control delimiters (e.g. "{" and "}" or ";") are on the same line as the conditional (e.g. "if" "else" "do" "while" "switch" etc.

      I try to keep the control delimiters in sync with the program flow. This means that they don't belong on the same line as the conditional, because they are only executed (yes, they can represent stuff that the program needs to do) if the conditional is true. If they were on the same level as the conditional, that would mean that they are executed regardless of the conditional, which isn't the case.


      if(condition)
      /* All of the following, up to and including the closing brace,
                  is executed only if condition is true. */
            {
            some_statement;
            }
      else
      /* All of the following, up to and including the closing brace,
                  is executed only if condition is false. */
            {
            other_statement;
            }

      yet_another_statement;

    258. Re:braces by sarabob · · Score: 1

      Buy a widescreen monitor with rotate. Rotate into portrait mode - voila!

      Unfortunately you become an 80-column nazi instead.

    259. Re:braces by zsau · · Score: 1

      The sixty-six letter limit has to do with dense text where you're basically reading a block of text line-by-line. If you go much above sixty-six letters you start having difficulty wrapping back to the next line properly (I personally find I can read much faster with an even narrower width, so I keep my webbrowser windows narrower).

      Computer programming is never formatted like that; instead you have lines frequently indented and of a very irregular length. The sixty-six letters might still hold, but I wouldn't count on it.

      Still, I like to keep my all the windows on my computer as narrow as possible, especially with wide screens. That lets me put two (or more) windows side-by-side and work much more productively. But I've found that the sort of syntax you get in C-like objected-oriented lanugages, like C++, Java and C#, makes it very hard to stick to the narrow line widths I like without breaks in ugly places. This is one (of many) reason(s) I still prefer languages like Haskell and LISP even though C# now has many features that make it work more like I think than C++ or Java.

      --
      Look out!
    260. Re:braces by dkf · · Score: 1

      Older compilers (and many current 8 bit) will generate a new stack frame for most nested levles of { where they couldn't tell if there was a new frame or not. Modern compilers see a much larger picture.

      If by "older compilers" you are referring to stuff that's older than 15 years, then maybe. But I can assure you that for as long as I've been programming that's not been true. The compiler might extend the current stack frame's size, but that's not the same as creating a new one. As I said, you can tell this because you can still see the variables in the outer context (also stack-allocated) without trouble; if you were in a new stack frame, that would not work without special shenanigans.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    261. Re:braces by zsau · · Score: 1

      I had written a detailed post in defence of the alternative style, but lost it when I accidentally closed the window just after previewing so the computer never prompted me about the changes, and I can't really be bothered writing it again. (Also, I reread your last paragraph and realise you might not like it, but maybe someone else will... Also, I like the sound of my own voice ;)

      Still, my main point was that putting the opening brackets on a separate line add too much space and make it look like the if line and the if branch are in separate paragraphs. This makes them look unrelated — whereas an if branch is almost always very strongly related to the if line — and so it slows me down. It's particularly bad when reading code by the those programmers who put any (intentional) pragraphs at all.

      As for making it harder to see where the if branch is/where things line up, which I suppose to be your concern... Indentation should tell me which parts of the code are part of the if branch, and which aren't. If it doesn't, the programmer's done something wrong, so what reason have I got to suppose they've put the brackets in the right places, regardless of where they're put? I rely on my IDE to tell me where the brackets line up, using highlighting/blinking and keyboard shortcuts.

      --
      Look out!
    262. Re:braces by totally+bogus+dude · · Score: 1

      The clearest way is whatever way you learned first when you were learning to code.

      Not always, when I learned C I used "K&R" style braces (i.e. on the same line as the if/else clause), but switched to "GNU" style braces (vertically aligned) after a few years because of encountering code that used that style and deciding I preferred it.

      There's good arguments for and against both styles, IMHO, so it just comes down to personal preference as you say.

    263. Re:braces by Anonymous Coward · · Score: 0

      I agree with you on the tab question. Tabulators are for indentation. I even use spaces in situations like your example. Phiew, I thought I was alone :)

      One of these days I'm going to try to modify an editor's view so you can set a "hide limit" which specifies how many tab characters you need until code is hidden in the editor's view, essentially letting you set a "complexity" or "detail" level in the view.

      like:

      original code:

      if (foo) {
              bar();
      } else {
              if (bar) {
                      quox();
              }
      }

      tab limit 1:

      if (foo) {
      } else {
      }

      tab limit 2:

      if (foo) {
              bar();
      } else {
              if (bar) {
              }
      }

      tab limit 3:

      if (foo) {
              bar();
      } else {
              if (bar) {
                      quox();
              }
      }

      oh well, one of these days...

    264. Re:braces by Anonymous Coward · · Score: 0

      Good point I have always thought that braces were a bit redundant my self. I do prefer the VB "End If", style at least that way when you are at the bottom of a method you know what is being closed rather than the usual C type languages whose files always end in the uninformative
                              }
                          }
                      }
                }
            }
      }

    265. Re:braces by nurbles · · Score: 1

      This mornonic argument to braces on their own lines keeps cropping up. I wonder if the writers realize that they are actually saying (well, ok, implying that the code should be written in paragraphs, with no vertical whitespace except perhaps between blocks. For example:

      int function( int arg1, char *arg2 ) { int b; for(b=0;b<100;b++){ arg1 += arg1%b; } arg1 += 2; arg1 = sqrt(arg1); arg1 = arg1 < 15 ? arg1 * 2 : arg1 - 3; /* yeah the loop is dumb, but I needed some statements to fill a paragraph up */ if( arg1 < 27 ) arg1 *= 3; else if( arg1 > 35 ) arg /= 7; else arg += 2; sprintf( arg2, "this is just more filler" ); return arg1; }

      Does anyone actually find that formatting code like text is a good thing?

      Code is something different and should be treated accordingly. The brace argument has its points on all sides, but in my opinion, the "braces of their own lines" schools have one important point that the "cuddled braces schools" cannot claim: when the blocks are very clear, the code is simply easier to understand for the next person to look at it. Before you argue, remember that I'm including programmers from both schools here... Regardless of your preferred coding style, you can read the "separate line" style just fine, and rather quickly (and if you have trouble remembering the extra few lines of code that may not be visible because of it, you might consider another line of work). However, people from the "separate line" school can have quite a bit of trouble reading (and therefore debugging/maintaining) code written in the "cuddled" style. Feel free to dismiss me, I'm only saying this based on 25 years of C programming experience, so I likely have no clue what I'm talking about.

      Luckily, many IDEs include a code formatter so that poor layout can generally be fixed to a more enlightened layout. And to some extent, event the venerable indent utiity can be used to do the same, though it seemed (in the past, at least) to have a bit of a bias toward cuddling.

    266. Re:braces by Anonymous Coward · · Score: 0

      The code is important. The braces are syntactical sugar.

      Syntactical sugar? If that were the case, you wouldn't need them.

      I can understand why you might say that. I cannot understand why that comment was rated as insightful.

    267. Re:braces by Ihlosi · · Score: 1

      The code is important. The braces are syntactical sugar.

      I take it that you've never looked at the disassembly ? That "syntactical sugar" can stand for quite a few assembly instructions.

    268. Re:braces by Nurgled · · Score: 1

      function(
      [tab]arg1,
      [tab]arg2
      );

      If it's a function declaration rather than a function call that's wrapping over multiple lines, you've got too many arguments!

    269. Re:braces by SamSim · · Score: 1

      If you have to split a function across two lines, you should indent it like this:

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

      Personally I do:

      {tab}function(
      {tab}{tab}arg1,
      {tab}{tab}arg2
      {tab})

    270. Re:braces by Veretax · · Score: 1

      Point of order, if you put the open brace on the end of any meaningful If Line, unless you indent all your code to line up to with it, then the indentation for finding the brace doesn't work. Sure it has no effect on the code, but that's not the point. Code needs to be easy for someone to come in and maintain. Furthermore when scrolling in code, its equally possible that while looking for the statement that lines up, you could skip up into a section of a code that is unrelated. Ergo. Putting it on a new line would help alleviate that.

    271. Re:braces by Veretax · · Score: 1

      I understand what your saying, but in my experience, its better to use braces even for one liners, because you never know when a simple single function call will need to be augmented to have more than one statement following the if. If you put the braces in ahead of time, you don't have to worry about making that change when it comes time for maintenance.

    272. Re:braces by Anonymous Coward · · Score: 0

      In my experience, braces and indentation are the two coding standard subjects most likely to cause physical fights between developers. I used to work with some Indian contractors, and while they were all good coders, for some reason they had the absolute WORST brace/tab usage I've ever seen.

      The stuff read like an e.e.cummings poem.

      (For the record: open brace goes with the declaration, close brace goes on its own line unless it's followed by an "else" clause. No special treatment for functions. And *always* wrap conditionals in braces, even for single statements... because you never know when you'll add another statement later on and break something by accident.)

    273. Re:braces by gfxguy · · Score: 1

      Indentation should tell me which parts of the code are part of the if branch, and which aren't.

      Except there are reasons to indent besides nesting level, like continuation of a long line.

      As a side note, I like at least having a choice. The people who created Python... I just don't know what to say. Mandating indenting style is just so... lame. When I'm writing Python code I feel like I'm back in my COBOL days.

      --
      Stupid sexy Flanders.
    274. Re:braces by Courageous · · Score: 1

      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.

      I have a mundanely mechanistic complaint with that.

      When reviewing someone else's overly long function, I will sometimes hover over the trailing brace in vi, then hit the "%" key. This will take me to the opening brace, but pan to the right. It jars, and doesn't help.

      Supposing I knew a keystroke that took me to the beginning of the statement that opened the curly brace... ...but I don't.

      On the subject of editors, I've often thought that an editor that knew all my blocks and did, on the far left, in a very very light color, a nesting diagram would be very useful. Alas... old and trapped in my ways, I still use vi(m).

      C//

    275. Re:braces by Surt · · Score: 1

      From another perspective:
      Modern ides are so good at restructuring code that code style is irrelevant. You should have your source control system restyle to the standard at checkin, and the individual developers' ide should restyle to their preferred style at sync/file open/checkout as they prefer.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    276. Re:braces by Surt · · Score: 1

      There are sound reasons beyond screen space for breaking long lines.

      Why isn't the editor automatically (optionally) wrapping lines to your window size, while also maintaining the proper indentation of that wrapped line? Any decent editor should allow you to set it to wrap at an arbitrary column number regardless of windows size, as well.

      Putting line breaks into text for anything other than signaling the end of a paragraph/statement is very 1980s.

      If editors could put braces where the reader expects them to be we wouldn't be reading this whole discussion.

      All the good ones can. People are just too lazy/scared to use this feature.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    277. Re:braces by Surt · · Score: 1

      Thank goodness most people don't make their style decisions based on what 3 year olds think. Their brains are a little under half full mass and don't have near the power of an adult brain.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    278. Re:braces by Vexorian · · Score: 1

      Of course, there's nothing wrong with C++'s implementation either, it 's the programmer...

      --

      Copyright infringement is "piracy" in the same way DRM is "consumer rape"
    279. Re:braces by Vexorian · · Score: 1

      Could you find a link or something? I am trying to find info on this behavior but I can't think of good search phrases it seems.

      --

      Copyright infringement is "piracy" in the same way DRM is "consumer rape"
    280. Re:braces by dunkelfalke · · Score: 1

      yep, same here.

      i started with pascal and this was the pascal preferred way. say what you want about pascal (i actually like the language) but it teaches good programming practices.

      --
      "It's such a fine line between stupid and clever" -- David St. Hubbins, Spinal Tap
    281. Re:braces by 0xABADC0DA · · Score: 1

      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.

      I would argue that it is the tab key on a typewriter or keyboard that has a well-defined semantic meaning. The tab character as in 0x9 has never been well defined.

      In fact, the characters below 0x20 are not even intended to be part of a body of text... they are control characters for manipulating the input/output device. For instance, you don't see people clammoring to use 0x1 "start of heading" to replace the <head> tag, or for that matter there is the confusion over ctrl-j and ctrl-m. The tab key, ctrl-i, should be regarded like enter or escape that performs a function, in this case the function of advancing to the next tabstop, and not as a character that does this -- enter might insert an 0xA, a 0xAD, or a 0xDA depending on the OS. In other words, having the tab cause spaces to be inserted into the document is entirely consistent with it's ASCII value as a control code.

      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.

      I don't think anybody really disagrees with that in theory, using tabs at the left to indent then switching over to spaces for aligning. The problem is entirely a practical one of mixing two invisible characters.

      I've seen way too many instances of "[tab][space][tab]" for a two-level indent, or other freakish combinations for me to be able to support tab characters in any form -- even though I agree with you and Linus that using them at the beginning makes sense. Except in something like the kernel where there is necessarily a lot of discipline I just haven't ever seen it work.

    282. Re:braces by vaz01 · · Score: 1

      This is all I can find...

      http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Non_002dbugs.html#Non_002dbugs

      This is gcc-specific and I'm not sure it totally proves what I was saying.

      Basically it says though that something like

      int i = 1;
      func(i++, i++);

      could end up being func(2, 3) or func(3, 2)...

      that might mean comma-separated expressions aren't inherently ordered.

    283. Re:braces by epine · · Score: 1

      The reason why 80 columns was chosen was because it was pretty universal - everything displayed in 80 columns.

      IIRC Apple ][ was 40 characters wide. TRS-80 was 64 characters wide. Osborne had 52 characters (and a bogus panning mode). There were many terminals and PCs that didn't display 80 character screens. And no end of early display calculators.

      More to the point, the human eye finds it increasingly difficult to move from the end of a line to the beginning of the next line in dense print where line lengths exceed 60 to 70 characters.

      It seems that half of all web designers who ever lived look at their creations with lorem ipsum filled in for the live text. Those tiny characters make the layout look so nice! Pity you can't actually efficiently read the content when the lorem ipsum loved by graphics designers is replaced by a reason to actually visit the page.

      My favorite Firefox function of all is text zoom. Except on those web pages where 120 character lines are etched in stone (font size computed as a percentage of display width).

    284. Re:braces by Anonymous Coward · · Score: 0

      Forth maintainable is not.

      Forth beautiful simplistic elegant and and is.

      Fortunately, modern Forth isn't constrained to 1024 byte blocks (64x16 editors, oh yeah) for disk i/o anymore, and things can be stretched out for some semblance of readability.

      Raise your hand if you miss --> . Nobody? Thank FSM.

      I'm still hoping that someday I can put my misspent youth in the caverns of Forth to profit.

    285. Re:braces by aj50 · · Score: 1

      If you're panning to the right then the line is too long.

      I also use vim but I'm still young and have no excuse.

      --
      I wish to remain anomalous
    286. Re:braces by defaria · · Score: 0

      Nonsense! The whole problem stems from the arbitrary distinction between single and compound statements. Let's take the if statement for example. You can do:

      if (cond)
          <statement>

      However if you need more than one statement then you need to use braces. Stupid! Why make this arbitrary distinction between single and compound statements. Stated differently, what if you always considered it a compound statement? Some languages do requiring that you instead terminate such statement so the compiler knows where it ends.

      Once you got in your mind that just because you can write the above, you instead won't ever write the above and instead always write compound statements you'll therefore always have the braces. Now you don't need to "line up" any statements because they are always compound and the brace then become syntactical sugar that just get in the way. So now you have:

      if (cond) {
          <statement>
      } else {
          <statement>
      }

      The "if" and the "} else {" become your delimiting lines and you now just concerned about the statements executed when true and when false. The syntactical sugar of braces is unimportant! What's important is (cond) and the 's as that's what the code is doing. The braces is what the compiler requires to understand what you mean. As a result you concentrate more on what's being done not how it's being done.

    287. Re:braces by nuttycom · · Score: 1

      That sort of misses the parent's point, though, doesn't it? In your example, if the 'else' was accidentally deleted, the code would not only compile just fine, but because you've got a comment starting at the same place as the 'else' should be, it could easily pass a cursory visual inspection.

      Count me in the braces-on-the-line-and-cuddle-else camp.

    288. Re:braces by Anonymous Coward · · Score: 0

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

      Can we all agree that, by definition, the purpose of a standard is to establish guidelines that everyone follows all of the time? Comments like what I have quoted are redundant and discredit the importance of the original topic.

      I mean, imagine legislators interrupting the discussion of a pending bill to explain to each other that "the law must be followed by everyone all the time."

      Yes yes, we understand that.

    289. Re:braces by xianvox · · Score: 1

      You're doing it right. :)

    290. Re:braces by Anonymous Coward · · Score: 0

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

      Yes, well, at the very least it would be much shorter that way.

    291. Re:braces by DaveV1.0 · · Score: 1

      You must be one of my cowardly, shit eating mod-stalkers.

      --
      There is no "-1 offended" or "-1 you don't agree with me" mod options for a reason.
    292. Re:braces by |/|/||| · · Score: 1
      Or really long method and argument type names. As a java developer I see a lot of those.

      public static SpecialGraphicsBuffer createNewBuffer(GraphicsConfiguration config, YouGetThePoint etc) {

      --
      [javac] 100 errors
    293. Re:braces by zsau · · Score: 1

      Except there are reasons to indent besides nesting level, like continuation of a long line.

      I've never found that to be a problem. It takes a fraction of a second to check to the end of the line to find out if there's a curly bracket there or not. (I also typically use a different level of indentation for wrapped lines; I prefer the style of indentation where things at the same level should start at the same part of a line, so if you have a long function you indent like so[*]:

      foodillyboodilly(bardillybodlily,
                      bazdilly(random, purple, frog),
                      splatdilly);

      rather than:

      foodillyboodilly(bardillybodlily, bazdilly(random, purple, frog),
        splatdilly);

      Again I think this is clearer and easier to read for semantic reasons.)

      [*] Well, approximately. /. seems to be eating some of the spaces so that it's not possible to make it line up.

      --
      Look out!
    294. Re:braces by Your.Master · · Score: 1

      Are you saying that great programmers blindly follow the mostly-irrelevant conventions of others?

    295. Re:braces by Dachannien · · Score: 1

      I see your point. I think it's just something to do with the braces themselves - they just seem typographically "loud" enough that my brain wants them treated in a special manner. I don't have the same qualms about placement of "then" and "end" in Lua, for example.

    296. Re:braces by Anonymous Coward · · Score: 0

      Indents and newlines? Who needs 'em!

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

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

    1. Re:JSF (Lightning II) coding standards by Anonymous Coward · · Score: 0

      Nice read. It's not unreasonable. About the only thing I can't stand is braces on separate lines, preferring:

      if( flag ) {
              salute();
      }

      But that's just me :-)

    2. Re:JSF (Lightning II) coding standards by Anonymous Coward · · Score: 0

      Name and address withheld.

    3. Re:JSF (Lightning II) coding standards by Kavli · · Score: 1

      Couldn't possibly agree more. In this example the if-statement defines the indentation reference. To place the opening brace on a new line on the same indentation level is superfluous. The only thing it adds is one extra line of unnecessary fluff in the code.

    4. Re:JSF (Lightning II) coding standards by sizzzzlerz · · Score: 1

      142 pages of coding standards with 220 rules formatted as a typical DOD document with section numbering, headers, and footers, and change pages. Something I'm sure each team member read cover to cover.

      I'd challenge any of the manager of the JSF C++ project to cite rule AV123 (or any other rule) without looking it up. Standards are a good thing but this is overkill to the n-th degree. It be interesting to survey the code generated from this project (assuming it was ever completed) to see how closely these rules were followed and how soon after the project began, deviations from it started to appear.

    5. Re:JSF (Lightning II) coding standards by mikael · · Score: 1

      Why not just have:

      if ( flag )
              salute();

      And save an extra line?

      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    6. Re:JSF (Lightning II) coding standards by Anonymous Coward · · Score: 0

      Actually, we do.

      You don't need to worry about citing it without looking it up, you just keep the code styles memorized, and flag anything you think looks funny, then go look it up later and cite it during the code reviews.

      Finished code (flight code) has no deviations.

    7. Re:JSF (Lightning II) coding standards by Catskul · · Score: 1

      That thing is so freaking long. Good luck getting your team to read it, much less follow it. We recently looked at using that where I work and it got tossed for that reason.

      --

      Im not here now... Im out KILLING pepperoni
    8. Re:JSF (Lightning II) coding standards by jez9999 · · Score: 1

      142 pages of coding standards with 220 rules formatted as a typical DOD document with section numbering, headers, and footers, and change pages. Something I'm sure each team member read cover to cover.

      Anyone who can learn C++ can learn that.

    9. Re:JSF (Lightning II) coding standards by joestoner · · Score: 1

      142 pages, sorry, it's more of coding nightmare to follow. Too many rules, and there are none. My recommendation is 1. Code should be easy to read. 2. Behavior straight forward, good class and variable naming. 3. If program is to complex, redo it to be simple, use Object orientation. 4. If the algorithm is still complex, write full pseudo code, before actual code. 5. Use comments for bug fix, date, name, revision, reason.

    10. Re:JSF (Lightning II) coding standards by Surt · · Score: 1

      Why not just have:

      if ( flag )

              salute();

      And save an extra line?

      Because you forgot part of the implementation, and it's particularly vulnerable to this bug:

      if (flag)
          comeToAttention();
          salute();

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
  6. 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".

    1. Re:Serious != good by Anonymous Coward · · Score: 0

      "constant variables"?

      Constant's aren't - variables won't.

    2. Re:Serious != good by gbjbaanb · · Score: 1

      Don't ever underestimate the value of 'easy to find'. I maintain code that generally has the same structure, so when I look at someone else's code, I know roughly where something will be. If (as happens with older stuff), they place the usual bits in other places, it can be nightmare to find.

      I think this doubly applies to OO languages, if you have an object full of static variables, you can have difficulty finding them. I'm sure if people had to write such code without an IDE to 'goto definition' then they'd revert to good, old fashioned styles like you complain about.

      It doesn't hurt to place constants in 1 place, even if they're declared globally. I'd say you coudl wrap them in a namespace, but they still remain in the same place so they're easy to find.

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

    1. Re:It's easy by Anne+Thwacks · · Score: 1
      Yeay, This is the best coding standard ever!

      Please can I wear unmatched braces while lighting the fire?

      --
      Sent from my ASR33 using ASCII
    2. Re:It's easy by Anonymous Coward · · Score: 0

      For a much greater symbolic gesture, instead of printing the comments, burn your pc while having them on the screen!

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

      "Well hung"..huh huh...

    3. Re:Well hungarian notation... by StrawberryFrog · · Score: 1

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

      You rename it.

      Is this common for you? Tell me the last time that it was a "really bad" problem. It's not common for me. In fact the only similar refactoring that I've ever seen used is the opposite: to extract an interface from a class.

      An interface is different to an abstract base class; an interface doesn't determine the base class heritage. If you make that kind of change, you should also be prepared to rename the interface/class.

      --

      My Karma: ran over your Dogma
      StrawberryFrog

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

    5. Re:Well hungarian notation... by QuietLagoon · · Score: 1

      I agree, Hungarian notiation is absolutely one of the worst coding standards I have ever seen foist upon innocent programmers. Sometimes I wonder if it alone is the reason why Windows is so unreliable, i.e., Microsoft programmers are concentrating too much on trying to get that prefix correct, and not enough on writing quality code.

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

    7. Re:Well hungarian notation... by Octorian · · Score: 1

      Also keep in mind that when you look at a C# class declaration, it isn't obvious whether something is extending a class of implementing an interface. However, Java class declarations do make this obvious. So in C#, the naming convention is more important.

      For example, in Java:
      public class Foo extends Foobar implements Stuff

      But in C#, you'd have:
      public class Foo : Foobar, IStuff

    8. Re:Well hungarian notation... by Anonymous Coward · · Score: 0

      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.

      Actually, I used variable naming convention way back in 1994 when developing database applications using Microsoft Access.

    9. Re:Well hungarian notation... by 75th+Trombone · · Score: 1

      Hungarian notation has a bad rap because the idiots who propagated it didn't understand English.

      Read Spoksky's article that talks about Hungarian, then come back and say it's harmful.

      --
      The United States of America: We do what we must because we can.
    10. Re:Well hungarian notation... by 75th+Trombone · · Score: 1
      --
      The United States of America: We do what we must because we can.
    11. Re:Well hungarian notation... by 75th+Trombone · · Score: 1

      You've not quite got it right; see my earlier comment.

      --
      The United States of America: We do what we must because we can.
    12. Re:Well hungarian notation... by QuietLagoon · · Score: 1
      OK, I read the article you site.

      .

      I still say it is harmful. Hungarian notation is way too complex. It makes it more difficult to write good code because you are thinking more about what friggin' prefix to use, and less about actually writing good code.

      You'll have to do a lot better than citing a random article to convince me that Hungarian notation is not one of the larger programming guidelines mistakes in existence.

    13. Re:Well hungarian notation... by ozphx · · Score: 1

      What happens when you make a serious change to a core identifier and don't give it a new name? It ends up named wrong?

      Good work there...

      --
      3laws: No freebies, no backsies, GTFO.
    14. Re:Well hungarian notation... by EvlG · · Score: 1

      That is a good article which explains how what he refers to as Apps Hungarian has an actual purpose.

      However, I am left wondering why not just define new types so that the compiler will tell if you create a bug?

      For example:

      class UnsafeString;
      class SafeString;

      And then you define your APIs in terms of the safe or unsafe strings, so that the user must use the conversion functions to go from one to the other.

      void PrintStringToHTML(SafeString arg1);

      In his other example, define coordinates for the layout versus the window as separate types, so that they can't be confused.

    15. Re:Well hungarian notation... by Shados · · Score: 1

      prefixing UI components drive me fucking batshit insane. You have an entire codebase where hungarian is prohibited, then the same people start prefixing variables, which really aren't any different from any other.

      If you're only using default Swing controls... ok, fine. Once you start mixing in 6 third party librairies, custom controls, etc, you seriously don't know what the fuck to name your UI components anymore.

      (Making stuff up here to make a point), you have a Panel, a Scrolling Panel, an Update Panel, a Flipping Panel, a Whatever Panel, then a Grid, a SuperGrid, a CoolGrid, a ReallyCoolGrid, a FancyGrid, and so on... what the hell do you start prefixing these things? If you prefix all grids the same, then it kills the point...if you don't, you have to start getting seriously creative. Just name them in things that make sense, and stay consistant with the rest (if its no hungarian, its no hungarian, UI or not). Why txtLogin? Wouldn't LoginInput make more sense? Why btnOk? SubmitInput, SubmitButton, whatever you wish that makes sense in that context... wouldn't it be even better?

      Like was already said too, in C#, the declaration for interfaces doens't easily allow to separate them, that why the I is there. It is an exception that I'm not sure should have been made, but now its there to stay... Though also keep in mind that in the .NET design guideline, you're never supposed to directly expose/return an interface in a public method or whatsnot... Always return an implementation. So interfaces will only be visible in the caller's code, or in parameters... in those cases, it is much less harmful.

    16. Re:Well hungarian notation... by Ken_g6 · · Score: 1

      It helps if you have a standard for your prefixes.

      Sure, txtLogin is what you call a TextBox for a Login, but what do you call, say, a ComboBox for a server?

      cmbServer?
      cboServer?
      cbxServer?

      I've seen both of the first two in the same application once.

      --
      (T>t && O(n)--) == sqrt(666)
    17. Re:Well hungarian notation... by spongman · · Score: 1
      because your new types will be incompatible with existing APIs especially those beyond your control (3rd party, OS, etc...)

      you could provide implicit casts for those types in order to remain compatible with those APIs, but then you're back where you started...

    18. Re:Well hungarian notation... by Anonymous Coward · · Score: 0

      The problem with Hungarian notation is really that most people have been soured on it because of being exposed to System Hungarian (largely thanks to Microsoft) instead of Applications Hungarian. System Hungarian uses prefixes for the underlying datatype, where Apps Hungarian uses prefixes for the variable use. System Hungarian often ends up being applied to every variable, even in stupid cases... Apps Hungarian tends to be easier to restrict to marking only specific types of variable use you might want to highlight for clarity.

    19. Re:Well hungarian notation... by nuttycom · · Score: 1

      The problem with that naming convention is that the user of the class shouldn't care about the distinction of whether a class implements an interface or extends some base class - in both cases it's an "is-a" relationship.

      "is a Stuff" makes sense to me. "is an IStuff" seems like it's revealing implementation details to the caller when it really shouldn't be.

    20. Re:Well hungarian notation... by hedronist · · Score: 1

      Huh. I was unaware of there being more than one variant of it. I had the "pleasure" of getting the original version straight from the horse's mouth.

      Charles was a real piece of work. His PhD thesis was on MetaProgramming and made the claim that programmers were interchangeable cogs and only the Uber-programmer (who directed all the drones) mattered. He even claimed to have proved it with an experiment involving programmers A, B, and C. There was one little tiny flaw in his experiment (other than the ridiculously small sample set). I actually know all three of the programmers involved and drones they ain't: one of them is possibly the best hacker I have ever met, and the other two are probably in the top 20. So, I guess if you have nothing but rock stars working for you then, yeah, they're interchangeable.

      Needless to say, Bill G. loved this idea and that's why Charles is now worth a few billion.

      Humorous note: There were 8 of us + Charles on the BravoX project. He was so undisciplined in using our primitive "source code control system" that we eventually locked him out of the code and he could only check things out with the help of one of his employees.

  9. 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 4D6963 · · Score: 1

      That quote isn't a rule to remember, it's just a basic fact. How does remembering that help a project avoid running into problems, and most importantly, do you even understand what a coding standard is?

      --
      You just got troll'd!
    2. 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.
    3. Re:My new standard by thogard · · Score: 1

      Because what you might call a coding standard describing how to format a line of code just happens to be a trivially small piece of the pie. The core involves design and implementation details. I look at so many projects today that are never done. They all comes from a lack of understanding the basics. We tend to throw new languages at problems in an effort to solve the real problems yet more and more projects are late, over budget and never fully complete. My core coding standard is "write it in a language where it can be finished" which is knocking out more and more of the trendy languages since you can't complete a project if its core run time keeps changing. I have written a number of programs that are done. They don't get updated, they don't need to since they just keep meeting their requirements decade after decade yet statement formatting wasn't a major issue with most of them and the ones that it did were languages that predate the free form concepts like FORTRAN on punch cards.

    4. Re:My new standard by 4D6963 · · Score: 1

      Ah, I see, makes more sense then. However it's hard to even read that between the lines of your original post ;-).

      --
      You just got troll'd!
    5. Re:My new standard by Anonymous Coward · · Score: 0

      My coding standard also comes from the 1950's, but it's kind of a pain to read since every line starts with "In my day", "You youngsters and your", or "You damn kids get off my lawn!"

    6. Re:My new standard by azgard · · Score: 1

      Programs consists of input, output, processing and storage.

      Modern programmers have improved upon this paradigm. Their programs consist of controller, view, model and XML.

    7. Re:My new standard by toddestan · · Score: 1

      Well, bickering about where to put brackets and else statements doesn't help you accomplish that. Personally, I don't see what the big deal is, and why some people seem to treat it almost as a religion. I have my preferences, of course, but I can adapt to how someone else likes to format fairly easily, so long as they are consistent with their style.

    8. Re:My new standard by 4D6963 · · Score: 1

      I agree wholeheartedly, but I don't believe that's what I was trying to say through my comment hehe.

      --
      You just got troll'd!
    9. Re:My new standard by vikstar · · Score: 1

      So true. I miss multiple return types in the popular C-derived programming languages.

      --
      The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.
  10. Enforcing dependencies with coding std.. by Anonymous Coward · · Score: 0

    One good coding standard is:

    The first line of foo.cpp has to look like:
    #include "foo.h"

    It ensures that foo.h is independent of other header files.

  11. [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 Anonymous Coward · · Score: 0

      Huh, I never realized the SS used java.

    2. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 0

      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.

      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.

    3. 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.
    4. Re:[Java] Use Checkstyle by Hermel · · Score: 1

      Enforcing braces is a good idea, I've seen the following class of mistakes too often:

      if (condition)
          statement

      is changed to

      if (condition)
          log("doing x")
          statement

      which obviously brakes the code. If you don't like the braces, you can often use ? and : instead.

    5. Re:[Java] Use Checkstyle by SirLurksAlot · · Score: 1

      First let me just say I love Checkstyle. It is a very handy tool, and I highly recommend it. That being said I really disagree with some of the rules you've stated there.

      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.

      Repeat after me: The method will be as long as it needs to be. While I agree with this idea in principle (in my experience) it usually doesn't hold up in a live environment. If a method can be easily broken into separate methods, great. If not, so be it. Sometimes things are complicated enough without having to jump all around the file finding particular methods.

      similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      Same argument as above, but at the project level instead of the class/file level.

      an upper limit on the allowed number of method parameters seems to be a good idea as well

      If you have to enforce a rule like this chances are you have bigger problems than just correctly formatting your code. This is more of a design issue than anything else, and anyone who is generating code with method calls that take ungodly amounts of parameters needs to be straightened out rather quickly.

      avoid star, redundant and unused imports

      Most modern IDEs will notify you that an import is unused or redundant, Eclipse is one of these.

      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.

      I've always found it to be very annoying when Checkstyle does this type of check. If I've written something a particular way I (usually) have a good reason for it. It is useful every now and then, but for the most part I just want to tell it I know what the hell I'm doing so leave me be.

      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)

      I'm of two minds on this. On the one hand I am on board with the "one way in, one way out" approach, but on the other hand it can be more efficient to simply exit the method when you're done doing whatever you need to. Creating a return variable is also taking up more space in memory, and having to follow the method to its completion can be time-consuming, especially when you need to check that nothing else is happening with the return variable before it exits.

      --
      God, schmod. I want my monkey man!
    6. Re:[Java] Use Checkstyle by roman_mir · · Score: 1

      * similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      - it is a stupid practice to set artificial standards on thing like file length. It didn't make sense during vi time, nor does it make sense today, when any decent IDE can hide/display file outlines, sections of code, comment blocks etc.

      same applies to any formatting basically, any IDE can reformat a source file to your liking. ( I only use tabs and always reformat code from spaces with an IDE, I hate spaces, you see. But if you want your spaces format it back with your IDE, or is that too hard?)

      same with import organization.

      same with the mandatory number of parameters - by specifying this you just provide justification for moron programmers to pass around lists/hashtables of parameters where not needed, thus hiding real method interfaces.

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

      - another silly constraint. Sometimes it makes sense to stop processing and exit without having anything else to do within a method, if this is not allowed the method will become more cumbersome by adding unnecessary control flow structures. You are complicating the code where it needs not be complicated.

      Automatically forcing 'final' on items may lead to bugs if a declaration is really not final, for example if the object is populated by reflection at some point.

      * we also constraint the if depth and boolean expression complexity to manage the cyclomatic complexity - also for easier reading

      - then you are doing this wrong as well. Forcing a particular depth of cycles/conditions is all great, except it does not provide a context for the reason of this action. I prefer to ask the developers to think in terms of business functionality. If loops and conditions are nested too deeply I ask to think for a reason why this may really be hiding a separate business function that even may be reused by another piece of code. Maybe it can be reused, maybe it can't, but the point is that in most cases deep enclosures are hiding some atomic piece of functionality that needs to be factored out and named and parametrized appropriately.

      Cheers

    7. Re:[Java] Use Checkstyle by illuvata · · Score: 1

      I've never really understood this problem. I mean, I can see how this could happen theoretically, but in practice are there any editors that wouldn't automatically turn the code into

      if (condition)
              log("doing x")
      statement

      thus making the problem trivial to spot?

    8. Re:[Java] Use Checkstyle by Lucas.Langa · · Score: 1

      First let me just say I love Checkstyle. It is a very handy tool, and I highly recommend it. That being said I really disagree with some of the rules you've stated there.

      And that's fine because they are not meant to be a global solution working in every case. In contrast, they were developed over the years and each of them can be easily backed up by examples and concrete reasoning. We had a group of rules we do not enforce nowadays because we found out that they weren't actually helpful. It's evolution, baby!

      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.

      Repeat after me: The method will be as long as it needs to be. While I agree with this idea in principle (in my experience) it usually doesn't hold up in a live environment. If a method can be easily broken into separate methods, great. If not, so be it. Sometimes things are complicated enough without having to jump all around the file finding particular methods.

      Of course, there is a small percentage of methods that cannot be easily separated. In fact, there are very few of them. All others can and should be refactored, if they are too long to read them without scrolling (that is usually ~70 LOC).

      You say that many short methods can make browsing the compilation unit harder. I disagree since when you read new code (e.g. written by someone else or written by yourself a long time ago), it's very easy to grab the meaning of what a public API method actually does if it doesn't do every low-level thing on it's own but delegates it to methods like "createProjectDirectoryStructure(...)", "for (File file : directory) { addFileContentsToSearchIndex(file); }", etc. etc.

      similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      Same argument as above, but at the project level instead of the class/file level.

      In our view, a vast majority of compilation units that are longer than 1000 lines screams for refactoring using the latest discoveries of the software industry called inheritance and design patterns. Usually a class ends up being over a thousand lines where refactoring wasn't done at the package/project level for a long time or the developer (yes, there can be more than one in a particular project) is not familiar with a design pattern that is just about the right solution for the fatness of the class.

      an upper limit on the allowed number of method parameters seems to be a good idea as well

      If you have to enforce a rule like this chances are you have bigger problems than just correctly formatting your code. This is more of a design issue than anything else, and anyone who is generating code with method calls that take ungodly amounts of parameters needs to be straightened out rather quickly.

      Sure, this is a design issue. It can arise after refactoring very old code, or when a previously unknown requirement is stated by the customer, or when you want to be compatible with some esoteric environment where the previous default behaviour wasn't enough.

      It's easier for people to just add another parameter and the hell with it. Remember that it doesn't have to be you who write the code. Note that even your code can later be edited by someone else. In time, this kind of "one small parameter more won't harm" change gets the code to a state where it's really hard to read and tends to be less performant. It's more of a watchguard for the things to come, not a guard for up-front stupid developers.

      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 hash

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

      * similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      - it is a stupid practice to set artificial standards on thing like file length. It didn't make sense during vi time, nor does it make sense today, when any decent IDE can hide/display file outlines, sections of code, comment blocks etc.

      No, it's not stupid because it has nothing to do with the ability to find what you're looking for by using Search/Replace, code folding, outlines, etc.

      However, this has to do with informing you that the size of your compilation unit probably means that you could use a little Gang of Four treatment or remind yourself how that useful thing called inheritance worked.

      same applies to any formatting basically, any IDE can reformat a source file to your liking. ( I only use tabs and always reformat code from spaces with an IDE, I hate spaces, you see. But if you want your spaces format it back with your IDE, or is that too hard?)

      If you have programmers smart enough to understand that code formatting is not a religion, and you pay them enough for their time to be of really significant cost, then you wouldn't want to let them reformat code back and forth and waste their time on it. And as experience shows, no-one really cries about it.

      same with the mandatory number of parameters - by specifying this you just provide justification for moron programmers to pass around lists/hashtables of parameters where not needed, thus hiding real method interfaces.

      That's a conjecture. Our experience shows none of your worries happen in real life. What happens instead is that the mandatory number of parameters makes the developers refactor their code properly instead of adding "just another small parameter" when a need arises.

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

      - another silly constraint. Sometimes it makes sense to stop processing and exit without having anything else to do within a method, if this is not allowed the method will become more cumbersome by adding unnecessary control flow structures. You are complicating the code where it needs not be complicated.

      Automatically forcing 'final' on items may lead to bugs if a declaration is really not final, for example if the object is populated by reflection at some point.

      You're right about the fast and unequivocal returns when some initial assumption is not met (like a parameter is null or a database connection is down). Then it's useful to have those.

      However, most of the time (and I really mean MOST OF the time) one return is what it should be. Marking fields final is as well, it enables compile-time optimizations, won't let you do stupid things like overwriting an internal state collection with another one, etc. Populated by reflection... really? How many times did you do that? Primo, this is a very special case. Secundo, in Java you can change the field state by reflection regardless whether fields are "final" or not.

      * we also constraint the if depth and boolean expression complexity to manage the cyclomatic complexity - also for easier reading

      - then you are doing this wrong as well. Forcing a particular depth of cycles/conditions is all great, except it does not provide a context for the reason of this action. I prefer to ask the developers to think in terms of business functionality. If loops and conditions are nested too deeply I ask to think for a reason why this may really be hiding a separate business function that even may be reused by another piece of code. Maybe it can be reused, maybe it can't, but the point is that in most cases deep enclosures are hiding some atomi

      --
      Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
    10. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 1, Insightful

      This is a Really Stupid Post, that I am replying to - a classically stupid post.

      1280x1024? I used to work as someone who audited code for a living - I read other peoples' code, cold (their explanations specifically could not be trusted, as we were looking for backdoors and such).

      Modularity negatively impacts readibility. You can't just read a module once and presume proper function. You have to carry in at least, example data from each reference to that function. In one case, we determined that a particular malformed date would allow someone to adjust their own balance. The date could not pass the web page audits, but could be driven in from a tool that could force arbitrary data into the post stream. Testers didn't find it because they were testing externals (i.e., web pages).

      It was almost impossible to find the interaction that allowed the balance adjustment, and it was heavily obscured by the use of modularity and objects. The coders had standards that had said that they could only have routines that were about the size of a page.

      So control flow jumped from routine to routine, and there were some routines that were split because they were doing complicated things, edits and stuff, that were too large to put into simple routines. Things that were data relative were pushed into data objects, and this just served to further obfuscate the situation-and slow the code.

      They would have benefited from longer pages, functionally sized modules, and standards that served them, ratherbthan vice versa.

      What they had was a rat's nest of modules and methods that met all their code standards and in which backdoors could be hidden, and it was impossible to say whether the backdoors were intentional or not.

    11. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 0

      similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      I've got C preprocessor macros which are longer than that.

    12. Re:[Java] Use Checkstyle by honkycat · · Score: 1

      Creating a return variable is also taking up more space in memory

      That's probably not true. I'm not 100% sure for Java, but any decent C compiler takes the existence of a variable as a suggestion rather than a requirement (unless you declare it volatile, or under other special circumstances). It'll detect that you're just setting the variable and returning without checking it again, and probably generate very similar code whether you use split returns or not. AFAIK there's no strong general technical reason to prefer one return convention over the other, it's purely a style/debugging/human comprehension issue.

    13. Re:[Java] Use Checkstyle by toddhisattva · · Score: 1

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

      Another benefit: it lowers the "cost of modification" if you brace even one-liners. They may not always be one-liners.

    14. Re:[Java] Use Checkstyle by SirLurksAlot · · Score: 1

      I'm admittedly not an expert on compile optimization, so what you're saying could very well be true. Still, even if the compiler will handle it behind the scenes I don't see any reason not to use multiple return statements where they make sense (arguments about readability aside).

      --
      God, schmod. I want my monkey man!
    15. Re:[Java] Use Checkstyle by SirLurksAlot · · Score: 1

      You make a lot of good points, and I certainly understand where you are coming from regarding refactoring, use of OO principles, and design patterns. It's great if your shop has the time and money to spend refactoring code, but for us at least that is a secondary goal and I'd imagine that to be the case for any number of other shops as well.

      I know what it is like to step into someone else's code (or as you pointed out, your own after a long period of time has passed), and while a full API is definitely useful to get to know the code it can suck when you start debugging it. Walking through call after nested method call can be a nightmare, especially if the codebase has been around for a while. I guess you take the good with the bad though.

      I don't disagree with you completely, after all it sounds like your shop has had a lot of time to refine its coding standards. I'm sure there are plenty of valid reasons for the rules that you pointed out, I just disagree with dogmatic approaches that focus more on idealistic standards than actually getting work done. I'm not saying your shop is or isn't dogmatic in its approach, but you hopefully get my meaning.

      --
      God, schmod. I want my monkey man!
    16. Re:[Java] Use Checkstyle by johanatan · · Score: 1

      Limiting multiple returns values and to a lesser extent number of input variables should not be on that list. This respect is one of the reasons that Python is such a productive environment.

    17. Re:[Java] Use Checkstyle by Lucas.Langa · · Score: 1

      You are right that stepping through a deep call stack can be irritating. That's why rather than do frequent debugging on the whole system / class / whatever, we try to do unit testing where possible and debug as little fragments of code as possible. Having quite short methods makes that nearly trivial most of the time. It isn't always possible so yes, at times we have to bare with the bad.

      Maybe the things I described here seem idealistic but in fact the best thing about them is that most of the deal can (and should) be automated. Even very complicated refactoring can be done by Eclipse or NetBeans, and while you must be careful (these tools are not perfect), they can do amazing things in seconds.

      We also hate formal idealistic approaches to problem solving which take too much time. But that's a completely different story. Dare to ask Slashdot? ;)

      --
      Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
    18. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 0

      enforce the usage of braces everywhere (e.g. disallow if (something) action; )

      Gah, I hate coders who use braces when unnecessary. Reminds me of a coworker of mine who once tried to enforce not using the ternary operator, with claims that it makes things too difficult to understand.

      // if you commit code like this:
      $qux = 0;
      if ($foo == 1) { // or if (1 == $foo) for you paranoid types
          $qux = $bar;
      }
      else {
          $qux = $baz;
      }
       
      // you're damn right I'm going to fix it to read:
      $qux = $foo == 1 ? $bar : $baz;

    19. Re:[Java] Use Checkstyle by honkycat · · Score: 1

      I agree, I generally think it's more sensible to code what you mean. If the purpose of a branch is to terminate the function early, why not just terminate the function with a return rather than introduce complexity within the function flow...

      It just bugs me when people try to justify stylistic decisions like that with pseudo-technical arguments. Don't mean to single out your statement, it just happened to be the one that I responded to. I've seen them on both sides of almost every stylistic issue -- everyone's got some "once-upon-a-time" efficiency argument to support their favorite style... most of these "issues" are at best woefully out of date, but live on solely in coding standards.

      The truth (IMO) is that code should be styled for humans to understand. O(1) efficiency sacrifices in favor of readability are usually a good trade-off until a profiler proves it's a bottleneck. The rub is defining "readability." (FWIW, I mostly support loose "common sense" style guidelines-- define whether indents are tabs or spaces and leave it to code reviews to catch egregious style violations)

    20. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 0

      I agree; that is pretty stupid. As a brand-new Java hire many years ago I was called over to a group of three people standing around a computer. They were trying to understand a line of the form:

      a=froo?bar:baz;

      Admittedly, this is a poorly formatted line of code: it needs six more spaces to be readable. Still, it was giving these three Java developers way too much trouble. They were arguing about whether ? and : were valid characters in a Java variable name. One guy said they were: "I thought they weren't either, but look: it compiles fine, so froo?bar:baz must be a valid identifier!" They called me over to help because I knew grep and could help them figure out where it was defined, since their IDE search function "didn't work" for this unusual name.

      As a result of this little episode, some people tried to declare ternary operators "too confusing" but the development manager made sure we all "accidentally" heard him make a few comments about "ignorant idiots" who didn't even recognize the operators of the programming language they were paid to know.

      That was the last really cool manager I had :-(

    21. Re:[Java] Use Checkstyle by Anonymous Coward · · Score: 0

      similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)

      I seriously hope you were just taking a swipe at Bill Gates' infamous quote with that line. Files are used to group logically related code. Big or small, it doesn't matter. Unless one is somehow stuck using Notepad as an code editor, code file size is a non-issue.

      Example: I work on a code base where single code files regularly exceed 32 kiB. According to this metric, I should break each of these into at least 32 files. This project already has over *ten thousand* honest-to-god code files, and you want me to increase that by an order of magnitude? Color me unconvinced.

      I understand the reasoning behind limiting function length (although I prefer "as concise as possible without obfuscating the logic" to a hard line limit), but that same reasoning does not apply as well to files. Take the code base I mentioned above: if I want to find out what method "foo" of class "Bar" does, I know I will find that method in the (single) Bar code file. If we were to impose file size limits, I might have to try a few files before I find the one containing the method. This improves neither efficiency nor understandability. Yes, a code browser could take me right to the method--but using a code browser also removes the reason for imposing arbitrary file size limits in the first place!

      I just don't see the point.

  12. The best coding standard is... by Anonymous Coward · · Score: 1, Funny

    the one that follows the code I write. Every other standard is crap.

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

    2. Re:developer buy-in by JaredOfEuropa · · Score: 1

      IOW, ask your developers to create the standard together.

      Better order a cage and have a few medics standing by for the inevitable K&R vs. ANSI style deathmatch.

      Coding standards should not optional, and you can and should enforce them. Just make sure that they are reasonable (i.e. not too loose nor to strict), make sense, and are the same across your organisation (don't let every project have their own standards). If a developer has a reasonable objection to parts of the coding standards, then it's worth listening to him and consider changes the standard, but if he refuses to apply the standard because he disagrees with some of its rules, then he's off the team.

      --
      If construction was anything like programming, an incorrectly fitted lock would bring down the entire building...
    3. Re:developer buy-in by Anonymous Coward · · Score: 0

      One of my current tasks is to enforce certain coding standards which the developers did not make up themselves. In particular security related coding practices. In our case the customer requires a secure coding standard be implemented. I have yet to encounter anyone on the team that has a problem with it.

    4. Re:developer buy-in by Anonymous Coward · · Score: 1, Funny

      400 quatloos on "Minwee".

    5. Re:developer buy-in by sizzzzlerz · · Score: 1

      If, after a style is imposed, a developer willfully chooses not to follow said style, they should go look for other places to work. They're professionals in a business environment and their personal desires must sometimes be suppressed. Just as they can't code up whatever program suits their fancy, how they do their coding can be dictated by those who pay the salaries.

      As far as a group hug approach to setting standards, its fine (necessary) to survey the troops for their ideas, but at some point, the person in charge must make the decision. Yes, people will be pissed that they may have to do things differently than they'd like but, see my first paragraph.

    6. Re:developer buy-in by canadian_right · · Score: 1

      Please! mod up.

      You have to enforce one standard. Even if it isn't my favourite.

      --
      Anarchists never rule
    7. Re:developer buy-in by pdh11 · · Score: 1

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

      If you do this, at least filter it past someone who's a language expert before casting it in stone. I once worked somewhere where the official coding style for C demanded that structs were declared like this: "typedef struct _Foo { ... } Foo_t". Either no-one knew, or no-one cared, that names starting with underscore are reserved to the standard library implementor, and that names ending with "_t" are reserved to Posix.

      As it turned out, namespace pollution ended up not being among this company's biggest technical problems, but it did make knowledgeable developers feel that their professionalism was being wasted.

      Peter

    8. Re:developer buy-in by B3ryllium · · Score: 1

      I'll wager 50 quatloos on the Python guy

    9. Re:developer buy-in by Anonymous Coward · · Score: 0

      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.

      You sir are clearly an experienced developer type. If I could remember my /. login I would mod this as +5, Insightful.

      Being someone who has had occasion to work with other experienced developer types, upon reading your comment I immediately got a perfect visual with included soundtrack.

    10. Re:developer buy-in by Xtifr · · Score: 1

      If any of them have been around long enough to have worked with a body of code that used an arbitrary mish-mash of different styles in different places, chances are very high they'll buy in to something, just to avoid that sort of mess in the future. When some guys are using four-space-tabs and some are using eight-space-tabs and some are indenting with spaces, the result is an unreadable mess whatever you try to use to view it. And, while I don't particularly care about brace placement, having seventeen different styles of brace placement in a single source file will make me tear out my hair and scream.

      Consistency is good (in moderation). If the members of your team really can't come to some sort of reasonable agreement, they probably don't belong on the same team, and should all go off and work for some company that loves prima donnas instead.

      Of course, Hungarian notation is a separate matter. People who prefer Hungarian notation should simply be shot. Quickly, before they have an opportunity to breed. :) That said, I have held my nose and written code using Hungarian notation simply because rewriting the whole system wasn't an option, and trying to remember which parts use Hungarian and which don't is something I don't want to have to deal with in the future, or force other people to have to deal with. Even something as gawdawful as Hungarian notation is better the nightmares and hair-pulling that randomly inconsistent code can cause.

    11. Re:developer buy-in by Magada · · Score: 1

      What's this I hear about 4-space tabs and n-space tabs? A tab is a tab is ONE character. If you have a retarded text editor that substitutes whitespace for tabs according to some rule you set, stop using it.

      --
      Something bad is coming when people are suddenly anxious to tell the truth.
  14. JSF Standards by OneMadMuppet · · Score: 0, Redundant

    Take a look at the JSF C++ coding standards - www.research.att.com/~bs/JSF-AV-rules.pdf - Stroustrup had a hand in them and our internal standards use them as a base.

  15. 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
    1. Re:precise spacing by TheRaven64 · · Score: 1

      Sounds like the coding standards were written by a Fortran developer, or the person was actually writing Fortran and didn't understand the difference between the language and the coding standards.

      --
      I am TheRaven on Soylent News
    2. Re:precise spacing by thogard · · Score: 1

      More like punch card cobal. Fortran didn't care about spaces at all once you got past the line number and comment section of the line. Nearly all other spaces where optional for most versions and there were a few versions where you could delete all extra spaces and the compiler would be happy.

  16. Hungarian notation by yanyan · · Score: 1

    Hungarian notation. Ugly.

    1. 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 ?
    2. Re:Hungarian notation by Anonymous Coward · · Score: 0

      Agreed. It shits me to tears, and is hands-down the worst standard of all time. I've even seen someone come up with their own incompatible version which is even worse.

        I've read that Simonyi insists that everyone missed the original point of his notation - i.e. it isn't to embed type information in variable names, rather it's intended for semantic information - but that's certainly how it's ended up being used everywhere I've seen it. That's what happens when your ideas escape your control.

    3. Re:Hungarian Notation by 75th+Trombone · · Score: 1

      You should read about the real Hungarian notation, instead of the pointlessness that got propagated as Hungarian.

      --
      The United States of America: We do what we must because we can.
  17. 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.

    1. Re:GNU Indent by __aapbzv4610 · · Score: 1

      yeah, I love the formatter in Eclipse. I just match it up to the company's coding standards, and (try to remember to) run the formatter before I check in my work too.

    2. Re:GNU Indent by marcosdumay · · Score: 1

      I really think that source control systems should have client side hooks. That way you could run ident autmaticaly on every commit and update, and decouple your style from the team's.

    3. Re:GNU Indent by ozphx · · Score: 0, Flamebait

      Autoformatting. The quickest way to break blame. Good going there faghat.

      --
      3laws: No freebies, no backsies, GTFO.
    4. Re:GNU Indent by Jesus_666 · · Score: 1

      I really think that source control systems should have client side hooks. That way you could run ident autmaticaly on every commit and update, and decouple your style from the team's.

      If Eclipse was either scriptable or could be called from the shell to indent a file, a simple script would do nicely. Actually, if it isn't possible to do this in Eclipse: Why so?

      --
      USE HOT GRITS WITH STATUE OF NATALIE PORTMAN (NAKED AND PETRIFIED)
    5. Re:GNU Indent by skeeto · · Score: 1

      The problem with automatically indenting on commit is that the programmer might not get a chance to make sure the indenter did things correctly. For example, when lining up some complex code, like a getopt_long() struct, a tool like indent will un-align it all. Generally, I wrap my getopt_long() structs in

      /* *INDENT-ON* */

      /* *INDENT-OFF* */

      Of course, correcting it is simply just another commit anyway. :-P

    6. Re:GNU Indent by marcosdumay · · Score: 1

      It is possible to do that in Eclipse, as it is possible to replace Svn, Git or watever to do it. It is just too much trouble to do for an entire team.

  18. Some stuff that was stupid by sconeu · · Score: 1
    1. You will put spaces around every parenthesis
    2. You will use braces for every conditional, even if it's one line
    3. You will put the constant on the left for comparisons. This one isn't bad in and of itself, it's an =/== fix, but combine with...
    4. You will always have a comparison, EVEN FOR BOOLEANS [i.e. if ( TRUE == someVal )]
    --
    General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
    1. 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.

    2. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      "if ( TRUE == someVal )" does not mean the same as "if ( someVal )". If you must use this style then write "if ( FALSE != someVal )".

    3. Re:Some stuff that was stupid by Cpt.+Fwiffo · · Score: 1

      Not necessarily the case.

      Comparing against constants also prevents nullpointerexceptions.
      Assume value is null:
      value.equals(constant) crashes, whereas constant.equals(value) does not.

    4. Re:Some stuff that was stupid by John+Hasler · · Score: 1

      2, 3, and 4 are excellent rules. 1 is just an arbitrary convention, but the code will be more readable if everyone does it the same way.

      --
      Warning: this article may contain humor, sarcasm, parody, and perhaps even irony. Read at your own risk.
    5. Re:Some stuff that was stupid by Haeleth · · Score: 1

      You will put the constant on the left for comparisons. This one isn't bad in and of itself

      Yes it is. It encourages a false sense of security, but totally fails to help in all those cases where the things being compared are both variables.

      Better by far to write things for human comprehension (constant goes on right, like in every equation you saw in school), and let the compiler warn you if it sees an = where it's expecting an ==.

    6. Re:Some stuff that was stupid by Chabil+Ha' · · Score: 1

      Not only that, but *not* following 2 has some interesting side effects. If you don't put braces on it and someone comes back later and adds another line to the conditional logic--and forgets to put the braces on--THEN you will have a big problem. The developer will have thought that the statement is part of that if logic, when in fact, it is not and will always be executed.

      Consider the following:

              if (foo)
                      doBar()
                      doBaz()

      doBaz() will always execute, even if 'foo' is false. In order to ensure that doBaz() only executes when foo == true, put the curly braces on. In practice, you are helping protect the code from logic errors.

              if (foo)
              {
                      doBar()
                      doBaz()
              }

      --
      We're all hypocrites. We all have hidden parts, it's the contrast between them that make us more a hypocrite than others
    7. Re:Some stuff that was stupid by General+Wesc · · Score: 1

      2. You will use braces for every conditional, even if it's one line

      ...because sometimes additional statements will be added later.

      I don't really follow it, but it's a pretty standard rule.

    8. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      You will always have a comparison, EVEN FOR BOOLEANS [i.e. if ( TRUE == someVal )]

      This one is ridiculous. I always explicitly use an equality operator for non-boolean types:

      if(pointer != NULL) /* even though I know this is the same as if(pointer)

      I find that more clear. But boolean types are yes/no questions, so why compare explicitly, especially if you properly named your variables?

      if(has_foo)

      It would take more effort (for me, at least) to parse that if there were a comparison against true/false.

    9. Re:Some stuff that was stupid by cyfer2000 · · Score: 1

      My compiler generate hundreds of warnings.

      --
      There is a spark in every single flame bait point.
    10. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      This also protects you from NullPointerExceptions when some inconsiderate person passes in null rather than a real value:

      @Test public void testNullPointer(){
              assertEquals(false, "".equals(null));
      }

      @Test(expected = NullPointerException.class)
      public void testNullPointerExceptionRaises(){
              String foo = null;
              assertEquals(false, foo.equals(""));
      }

      Thus you can write

      if(CONSTANT.equals(param)){
          doStuff()
      }

      Rather than having to write:

      if(param != null && param.equals(constant){
          doStuff()
      }

    11. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      Rule 1 isn't completely obnoxious, but I prefer to leave that to individual taste. I have my own standard of course:

      Rule 2 makes sense in a multi-branch version control environment that's suffered merge errors in the past. That's why we use it at my work.

      Rule 3 is obsolete. My work uses rule 3, but gcc has warned against this kind of error for a decade at least, and the solution is less readable. You are using "pedantic", aren't you?

      My argument against rule 4 is that the extra code is just as likely to introduce more bugs than it solves. It's less readable too IMNSHO.

      If we turned on warnings here we'd be swamped with messages from the horrors in the existing code base (don't get me started about Japanese code), which makes a mockery of whatever coding standard they adopt. However, I always build new code with "pedantic" & "-Wall".

      In fact as far as I'm concerned until a suite builds clean with those settings, it's buggy. But this is more development standard than coding standard so I digress.

    12. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      People who compare with Boolean constants (when they do not have to do so by their coding standard) Really Never Got It. They never understood that Boole described an algebra. They cannot write down "if a implies b" or "x if either a or b". And so they prevent me from writing a concise "if a b" (this is Pascal and will not work reliably in C). For them something half the length of War and Peace is easier to understand.

      Such people should be banned from using multiplication (that's an algebra, too) and do everything by addition until They Get It. Unfortunately addition is an algebra, too.

    13. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      Sorry, code got mangled.

      That should have been "if a <= b" or "x := a <> b".

      Which gives me the chance to say more:

      if (TRUE == b)

      does not work reliably in C. TRUE is typically #defined as 1. However, C interprets any value other than 0 as true. So if b happens to be 42...

    14. Re:Some stuff that was stupid by Anonymous Coward · · Score: 0

      1. is a case of programmers thinking they know better than typesetters (they don't).

      3. dates back to the old days when C compilers did not mind "if (a = 0)", but these are the new days. Compilers give warnings on encountering the above. 3. can be subsumed under "Enable the warnings and heed them."

      4. may break your C program.

  19. Worst by Anonymous Coward · · Score: 1, Interesting

    The worst example I ever saw was some IBM Federal Systems code written in the 1970s -- they enforced the "one page module" rule using nested includes -- NINE LEVELS OF NESTED INCLUDES!! Of course, this was coded in a FORTRAN-like MIL-SPEC language with eight character filenames, so you can guess how hard it was to find a particular module. It was at least three levels down to find the first page of global variable declarations.

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

    2. Re:badness abounds in visual basic by Shados · · Score: 1

      The VB community is half the reason you need coding standards in more modern (or mature) ecosystems. With the popularity of VB6 or VBA + Access, there's a good chance that half your programmers with "senior" level experience (I use the term loosely) did stuff in VB...

      And coding standards in VB weren't "This is our VB coding standard for our internal projects". No. They were passed down as "This is the universal way to code, period". So you have a bunch of devs in C++/Java/.NET/Python/Whatever who start prefixing all their crap like they did in VB (which gets quite...entertaining in real OOP environment, because with 1-3 letter prefixes, you have to start getting REAL creative to prefix everything...and often the prefix becomes 'obj'...oh yeah, thats descriptive), then use the same coding standards in SQL (wtf...), as you pointed it, put error handling -EVERYWHERE- (oh yeah... try/catch on every SINGLE function... BYE BYE STACK TRACE! ::sniff:: ).

      I recently had to clean up a C# app like that... I seriously had to ask my manager for an extra week to familiarize myself with the app when I started my contract, because the conventions -seriously- got in the way of readability. (For example, in C#, virtually any public field will be implemented as a Getter/Setter public property... however, this guy exposed public variables directly... and often did it with lower case named variables, which is usually reserved to private fields...).

      I had to buy (with my own money) Resharper just so I could read and follow the code. I hate ex-VB6 programmers so much (ironic, since I've been there for a while...)

    3. Re:badness abounds in visual basic by Shados · · Score: 1

      Hahaha... I'm not a native english speaker either (though 90% of my life for the last 10 years has been in english... marrying a new yorker does that), and I have the exact same issues =P With those exact 2 cases, too.

    4. Re:badness abounds in visual basic by cjjjer · · Score: 1

      Sorry I beg to differ as I am a ex VB3, VB4, VB5, VB6 programmer. I now program in C# and VB.NET (depending on clients requirements). Bad programming has nothing to do with language but more to mentality. You have two types of developers' status-quo and ones who take pride in their work. It's the status-quo developers that tend to "cut and paste" and "short-cut" their way through their work which leads to crappy code.

    5. Re:badness abounds in visual basic by Shados · · Score: 1

      Oh, I know there are good developers that come from everywhere. I am an ex VB programmer myself :) But unless you were really sheltered from the VB community back then, you have to remember the forums/newsgroups (or before those were common place) the conventions, and the general mentality around it. It was pretty f****** bad. And since .NET was advertised heavily toward that community, you have one big mess (especially in the VB.NET world now).

      As a .NET consultant now, I systematically refuse to take jobs where VB.NET is the main setting, simply because the odds (notice I'm not talking about certainty) of having to work on a totally horrible codebase ported from VB6 with a mess mashup of hugarian notation and other things that totally ignore the .NET guidelines is simply too high. (Still too high for my taste in the C# world, but I manage...somehow...)

      If you're an ex-Vb6 programmer who is now working in .NET, and actually know that the framework design guidelines exist, and have heard (not necessarly used! I'm not that picky) of FxCop/CodeAnalysis.... well, that makes two of us :)

    6. Re:badness abounds in visual basic by obarel · · Score: 1

      Sounds like the company was destroyed by stupidity. I wouldn't blame coding standards...

      I have worked in a few companies (most weren't very successful). Although the code was never perfect, the problems were always elsewhere.

      It takes a very special company to be destroyed by bad technology alone (i.e. everything else, including the people, is perfect). It takes an even more special company to be destroyed by "important" stuff like braces, variable names or even the odd goto here and there. In most cases it's the over-promising, panic-mode-all-the-time, bad budgeting, bad communication and general stupidity that destroys companies.

    7. Re:badness abounds in visual basic by magus_melchior · · Score: 1

      I'm no Microsoft apologist, but this is more of a case of PHBs believing they have technical expertise ("look at my Microsoft certificate, you sniveling geek") that in reality doesn't exist.

      Look at it this way, had they used Unix as you suggested and still kept you out of the design loop, they would've coded something that nuked / on the POS and the servers, because of course they'd set the default user as root. I mean, any monkey who would delete a file on an error instead of closing it would go the whole 9 miles when given more power.

      --
      "We are Microsoft. You shall be assimilated. Competition is futile."
    8. Re:badness abounds in visual basic by Anonymous Coward · · Score: 0

      That can happen on ANY platform, not just Microsoft, OR with Microsoft tools... bad leadership & 'bad coding' can happen on *NIX, VMS, OS400, Z-OS (you-name-it).

      Your post sounds TOO MUCH like you are a "microsoft hater" (as seems to be the case around here quite a lot - "any opportunity to put down MS? Please do so, & you are VERY WELCOME over @ /. by all means, incidentally" etc. et al) is all I am saying...

      I've been there myself though, & even was FIRED for it once... I could not believe it (had to do with their network security, & especially @ the "end points" (user workstations)).

      ---

      E.G.-> Yes... I've been in pretty similar circumstances, & I was the one that got hurt by trying to help (even though I was hired for security of code mostly, I saw & found problems in their network security (endpoints, AND, that their TREND ANTIVIRUS was setup wrong, & months behind in updates)...

      After that?

      Heh - I gave up trying to advise those with problems of that nature, unless asked to do so... SPECIFICALLY.

      See... I've found that most folks (especially mgt.) can't handle it well - especially if a 'screwup' on their part in bad decision making causes problems. They don't take kindly I have noted, to showing them better or smarter ways of doing things (even ones you can quantify with concrete examples, for instance... even using things like multimedia hi-res timers & showing improvements in function/procedure/subroutine speedups, for example).

      E.G.=> Most MIS/IS/IT mgt. I have encountered haven't done the job in coding professionally themselves for YEARS to DECADES, first, & they tend to be easy to 'fool', or 'mess with' (such as giving ridiculous time to delivery schedules, too long etc.) - & when they find out they made bad decisions & others tried to warn them? They will dismiss that person, as quickly as possible, to cover their ass (remove a witness, so-to-speak).

      ---

      A pal of mine once said this to me:

      "Don't 'f' with mgt., even IF you are right + can show them CONCRETE & VISIBLE improvements (for little outlay of effort or resources)... They'll screw you outta a job - even IF you're trying to help them, & their cronies/sycophants/yes-men - they'll mess it up themselves, sooner or later & then they'll only have themselves to blame. If you tried to show them a better way & this comes out (especially if they didn't take your advice)?? They'll either promote you into THEIR jobs, dispensing with them, OR the company will die"

      ---

      That happened to me, I got terminated for making a set of SIMPLE suggesitons (was told @ first, it would 'cost too much in man hours to implement' which was b.s., via some .reg file merges via logon scripts & patches etc. + network settings @ endpoint nodes/workstations/printers, etc.) for it...

      Man, I could not believe it (especially considering I was brought in for security coding reasons, & many of my suggestions for the network guys were used too, which we had a Wed. a.m. meeting on this, reviewing what others were up to, & make suggestions to they if they were in a 'pinch')...

      In your case, it was the latter (no more job due to company failing) - the worst really, worse that being fired imo... too bad.

      APK

    9. Re:badness abounds in visual basic by julesh · · Score: 1

      I had to buy (with my own money) Resharper just so I could read and follow the code.

      I'm sorry... you work for a company so stingy that it won't buy a $350 piece of software that _saves it employees time_. I don't know about you, but I estimate working with resharper (particularly its error-fixing capability) saves me about half an hour of work per day. At that rate, it pays for itself in weeks...

    10. Re:badness abounds in visual basic by Ihlosi · · Score: 1
      At that rate, it pays for itself in weeks...

      From the companys point of view: If you can get the employee to buy it with his own money, it doesn't have to pay for itself at all and you still get the productivity increase! Isn't it nice to have suckers for employees ?

    11. Re:badness abounds in visual basic by Anonymous Coward · · Score: 0

      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)

      This is why I avoid all but the most common acronyms, or at least, spell it out in full the first time. POS, for example, can mean "piece of shit," or "point of sales." MP can mean "member of parliment," or "military police." In my most humble opinion, it is never a good idea to obfuscate the language even if we can usually determine the correct meaning from the context.

    12. Re:badness abounds in visual basic by mgiuca · · Score: 1

      But how does a company get to be Microsoft centric? I don't get it.

      Last year for a university project, I worked for a client who ran a software company. He demanded we use .NET to write a web service. Not just content with us using Microsoft, he would preach for hours whenever we met about how Microsoft was Great. How Microsoft "Just Worked". (Well that wasn't our experience).

      It wasn't just a case of "Use Microsoft .NET and Microsoft SQL Server". It was "For any given technology decision, use a Microsoft solution if possible, or if not find another solution." (This was literally our mandate).

      I can understand if a person/company loves .NET. Or loves Visual Basic. Or loves any particular product, because of its merits. But I don't get how you can blindly follow a single company and favour all their products over competitors. It just doesn't seem like good business.

    13. Re:badness abounds in visual basic by Anonymous Coward · · Score: 0

      In business software terms, POS stands for Point Of Sales. Basically a front line sales package: Order Entry, Customer Information, ...

      Quite often the other abbreviation is equally valid.

    14. Re:badness abounds in visual basic by sheldon · · Score: 1

      As a .NET consultant now, I systematically refuse to take jobs where VB.NET is the main setting, simply because the odds (notice I'm not talking about certainty) of having to work on a totally horrible codebase ported from VB6 with a mess mashup of hugarian notation and other things that totally ignore the .NET guidelines is simply too high. (Still too high for my taste in the C# world, but I manage...somehow...)

      Amen! Although to be fair, Hungarian notation started out as a C++ thing, not VB.

      The thing I hate most is the DNA style of building apps. Creating these layers of business objects that do no business other than acting as an abstraction layer to the data layer and all the business stuff up at the presentation layer. This was right out of some Microsoft textbook in the late 1990s, and the pattern still exists.

    15. Re:badness abounds in visual basic by Shados · · Score: 1

      Hungarian notation did start out pre-VB, but as a general rule, non-VB devs understand what it is, a convention that had advantages and drawbacks, and that often it is not a good idea to use it anymore. Most VB6 devs learned it as a rule at the same level as "no goto". A hard rule, that applies to programming as a whole, and is absolute. I recently had to explain to a former VB6 dev turned C# consultant that, and his reaction was literally like if I was telling him that the earth was flat. Looked at me like I was an alien.

      As a secondary side note, the layers of business objects as you call em, don't come from MS either (actually, as a general rule, while it is in the MS textbooks, the Windows development community is incredibly resistant to it). It is more omni present in all "business" type development environment, in general to reduce the pain of maintenance 10 years down the road.

      Now, if its overdone or not, I'll leave that to you =P

    16. Re:badness abounds in visual basic by Anonymous Coward · · Score: 0

      I used to think POS was "piece of shit" since its usually being used when talking about software (failed software).

      It is.

    17. Re:badness abounds in visual basic by sheldon · · Score: 1

      I honestly don't mind the prefixing if we're talking objects on a page. Like txtEmail which refers to the textbox containing the email address. But I don't need a variable called strEmail to contain the email I'm going to do something with.

      After reading that Spolsky article I can definately see using a usEmail as the variable name to indicate it's unsafe and came from user input though.

      As far as the business objects are concerned, I'm not talking about genuine business objects. I'm talking about apps where all the business logic is really in the presentation layer, and they create a BO layer which does nothing other than redirect to the data layer. Generally the datalayer returns a dataset, and this BO layer just passes the dataset back up to the page which then manipulates it and does something with it. It serves little purpose, but it's all over the place.

      By using an MVP pattern, you break this stupidity. Your view then is nothing but a series of events and properties that are nothing more than wrappers around the view objects(text boxes, labels, etc), and the Presenter layer has the business logic that either has handlers for those events, and sets the properties on the view as appropriate. What's nice about this pattern is you can build a mock view which allows you to test your business layer with unit tests. Extend this concept further by creating a mock data layer which has an in memory database, and you are in unit test heaven. That actually reduces the pain of maintenance 10 years down the road.

  21. 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.
    2. Re:Correct focus by WuphonsReach · · Score: 1

      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.

      Ding! Most definitely!

      One of the things that I learned from working over the years is that the most useful processes and guidelines have built-in safeties against simple errors. They're not guidelines for the sake of making things pretty, the underlying goal is to prevent easily avoided problems. Or making it easy to spot problems.

      A simple example of this is that any two identifiers should differ by at least two characters. Which prevents a single typo from resulting in using the wrong identifier. A rule that was more useful in the days before IDEs and auto-complete, but is still useful when it comes to naming project files or data files.

      --
      Wolde you bothe eate your cake, and have your cake?
  22. 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.

    2. Re:Embedded Coding by JPEWdev · · Score: 1

      We do the same thing: functions and varibles that are local to a specfic file (i.e. helper functuions) are declared "static", and are not required (or allowed) to have the module prefix.

  23. As long as the bosses remember that... by itsdapead · · Score: 1

    Guidelines and standards[1] are not rules. Rules are much harder to write because they have to anticipate every possible eventuality. The purpose of guidelines is to make people think good and hard before breaking them[2].

    Never did understand the fuss about GOTO... you need them everywhere in machine code, FORTRAN and (original) BASIC because that's the way the language works. Its perfectly logical to use them for exception handling in C or Pascal (and it was childish of "standard" Pascal to implement them in a deliberately perverse[3] way) and if you are using a language with decent structures and exception handling, the need just doesn't arise.

    [1] that's "standards" in the sense implied here rather than the W3C sense. God! I almost said ISO there, have to break that habit...!

    [2] Actually, I think the original Pratchett quote I've pinched was talking about rules but lets not be too subversive...

    [3] In "standard" Pascal you had to use numerical labels which had to be declared in advance...

    --
    In a survey of 100 programmers, 111111 thought that duck-typing was a good idea.
    1. Re:As long as the bosses remember that... by azrider · · Score: 1

      you need them everywhere in machine code, FORTRAN and (original) BASIC because that's the way the language works

      More importantly, that's the way the language works. Each jump or longjump is a GOTO. Each function call in a program is a GOTO (or GOSUB).

      When you have to unconditionally exit a set of nested condition tests, you either code explict tests all the way down the line or GOTO to escape.

      There is a difference between:

      GOTO should not be used

      -and-

      GOTO should not be used unless it results in cleaner, more understandable code

      --
      And ye shall know the truth, and the truth shall make you free.
      John 8:32(King James Version)
    2. Re:As long as the bosses remember that... by azrider · · Score: 1

      More importantly, that's the way the language works.

      Oops, meant that's the way the machine works ;-)

      --
      And ye shall know the truth, and the truth shall make you free.
      John 8:32(King James Version)
    3. Re:As long as the bosses remember that... by pablomme · · Score: 1

      Never did understand the fuss about GOTO... you need them everywhere in machine code, FORTRAN and (original) BASIC because that's the way the language works.

      Perhaps you may be able to say you need them in Fortran 77 and before, but certainly not in later versions.

      The fuss about GOTO is that people used them everywhere compulsively, making the code impossible to read. As an example, try to read the body of routine NL2ITR in NL2SOL and see how long it takes you to understand the flow of control. Good luck.

      --
      The state you are in while your HEAD is detached... - wait, what?
    4. Re:As long as the bosses remember that... by pablomme · · Score: 1

      Each jump or longjump is a GOTO. Each function call in a program is a GOTO (or GOSUB).

      Which is why we have compilers to take care of that mess.

      --
      The state you are in while your HEAD is detached... - wait, what?
    5. Re:As long as the bosses remember that... by itsdapead · · Score: 1

      Perhaps you may be able to say you need them in Fortran 77 and before, but certainly not in later versions.

      Sadly, they named the proposed new version "Fortran 8X" but forgot that X was pre-defined as floating point: consequently, a rounding error prevented them from converging on a standard. By the time Fortran 90 came out, everybody was too busy worrying about Object Oriented Programming to ask grandad what he did in the GOTO wars.

      see how long it takes you to understand the flow of control. Good luck.

      The question is, does the author of that use any other languages, and does he/she use GOTO in those?

      The "Pascal" versions of the FORTRAN 77 code in my late-80s copy of Numerical Recipes aren't very Pascal-like, but they don't use no stinkin' gotos!

      --
      In a survey of 100 programmers, 111111 thought that duck-typing was a good idea.
    6. Re:As long as the bosses remember that... by pablomme · · Score: 1

      The question is, does the author of that use any other languages, and does he/she use GOTO in those?

      I don't know, this is an ACM TOMS routine which dates back to 1981 (so I would guess they didn't use much besides Fortran). It does its job beautifully and is still widely used.

      My point is about how difficult it is to understand a piece of massively GOTOed code, and this is a great example of that. It is also, unintendedly, an example of how "bad" coding practices can still produce excellent software.

      --
      The state you are in while your HEAD is detached... - wait, what?
    7. Re:As long as the bosses remember that... by Anonymous Coward · · Score: 0

      [3] was meant to make you think before adding another label.

      So in the days of punch cards, a fellow student thought long and hard, and reused the following cards for all his programs:

      PROGRAM P(INPUT,OUTPUT)
      LABEL 1,2,3,4,5,6,7,8,9,10,11,12,13,15,
      (you get the idea)
      97,98,99;

      He was somewhat upset that you couldn't write LABEL 1..99;

  24. should use software to enforce standards by petes_PoV · · Score: 1
    Most places I've worked that have emploted coding standard require the code to be "eyeballed" in order to enforce them. While this is adequate when a project starts out and there are o time pressures, the standards tend to lapse as deadlines approach. No manager is his/her right mind wants to be the person who delays a project and certainly not because the code isn't indented properly.

    If you're going to have standards, they need to be enforced. the best way to do that is to have any style elements created by software, so the coders can write in their own way, but the house style is what's delivered to the client. This includes file headers, disclaimers and copyright statements.

    Of course the one place where coding standards never seem to apply is after the code is written, when the patches and bug-fixes are added.

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
  25. Secure Coding Standards by Anonymous Coward · · Score: 1, Informative

    For anyone coding C or C++, I strongly recommend CERT's secure coding standards:
    https://www.securecoding.cert.org/confluence/display/seccode/CERT+Secure+Coding+Standards

  26. Code reviews required before checkin by Anonymous Coward · · Score: 0

    In theory, a good idea. Code reviews are a good thing. Not releasing unreviewed code (at least for general, not testing use) is a good idea. The company even had a system set up for requesting and tracking pending code reviews.

    In practice, however, nobody gets around to reviewing anyone else's code for weeks or months after the request is made. Meanwhile, if you're a prolific coder, you've wound up with patches building on patches of patches that are built on other patches.

    When someone finally gets around to the review, they either don't review them in the order they need to be committed (approving things that can't be committed until something else is reviewed), or they have you change some things in the earlier code that causes a cascade of having to merge changes, regenerate patches for all those pending reviews, resubmit them for review (particularly fun if they've already approved something that had to change), etc.

    Proper approach: use development branches, review requests made in parallel with checkins, changes that come up in review open new cases/tasks, development branch collapsed once all the pertinent reviews are approved.

  27. Goto's can be useful by theblondebrunette · · Score: 1

    Not to start a flame war here, but goto's are used at some large companies. Their usage is strictly for error handling, like if (error) goto exit; Usualy same companies use a single return at the end of the function. I've seen this later part at more than one company being used.

    One benefit in using "goto exit", is that compiler/optimizer recognizes labels like exit, errorExit, etc. and considers them to be less likely to happen, thus allowing for more optimal code execution.

    I'm not familiar with exceptions in C/C++ well, but from what I've heard they're more expensive than a simple goto. For performance sensitive code, you cannot afford this.

    1. Re:Goto's can be useful by JPEWdev · · Score: 1

      We're allowed to use goto to break from a double loop instead of using a boolean flag.

      i.e.

      for(i = 0; i < N; i++)
      {
          for(j = 0; j < M; j++)
          {
              ...
              if( foo )
              {
                  goto end;
              }
              ...
          }
      }
      end:
      ...

  28. Simple standards are best by Ceallach · · Score: 1

    1. KISS - Keep It Simple Stupid, don't be unnecessarily complex.

    2. DRY - Don't Repeat Yourself, if two or three places perform essentially the same actions then that should be one function/method with the differences added and commented.

    3. Make it easily readable. This means simple yet meaningful variable names, comments where anything non-obvious is done and appropriate use of encapsulation/isolation (no methods/functions that are too long, and none with only one or two actual lines of logic).

    Anything else can fixed with a code beautifier/pretty printer/reasonable IDE or editor.

    --
    -- More Smoke! The mirrors aren't working!!!
  29. K&R by bugi · · Score: 1, Troll

    K&R style is all you ever really need.

  30. Standards have to be grown by russellh · · Score: 1

    The only coding standards that I think work are ones that are developed over time by coders and their managers together to solve specific problems.

    --
    must... stay... awake...
  31. 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.
    1. Re:No standard is a good standard by Shados · · Score: 1

      I'd extend what you said to "Anything that ends up public" (public here meaning the programming language term...as in , may appear in another "file" that uses stuff from your code)

      Anything defined public cannot be contained within "a single file", so it will quickly become a mess if it doesn't follow a certain standard. Then add exceptions, which aren't public but will bubble up..so your exception handling has to follow some kind of conventions to be consistant. Then localization: since the thread properties cross boundaries and will affect your code, and so will string ressources, etc. All multi-threaded code that may have public side effects...and so on.

      Thats why you end up with a coding standard... a lot of stuff ends up having the same ramifications as naming conventions for public APIs :)

    2. Re:No standard is a good standard by smartin · · Score: 1

      Not true, the way I code is the correct way, anyone that does it differently is wrong and should change. :)

      --
      The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
    3. Re:No standard is a good standard by gbjbaanb · · Score: 1

      I have had the good fortune to be able to write coding standards, and I totally agree with you. All the standard standards don't really help write better code, and I think they're just there to boost the ego of someone who thinks he's somehow better than the serfs who have to follow them.

      My standards ...
      . Keep your code the same style as whatever you're work on.
      . Ensure it gets checked in in the correct place in source control.
      . Make sure there is a (standard-format) readme file in the release directory, and a paramater xml, and binary.
      . Make sure you have put some comments in there (that's really to stop the cowboys just hacking out code withotu thinking)

      I find the rest falls into place anyway, even APIs as developers tend to keep to the existing styles anyway. If someone did start to do things differently just to be different, he'd have to have a talking to.

    4. Re:No standard is a good standard by ThomsonsPier · · Score: 1

      Hear, hear!

      Any programmer who is incapable of reading code because the white space is arranged slightly at odds to his preference has too little competence to be called a programmer.

  32. no coding standards at all by david_bonn · · Score: 1

    Honestly, I can't think of a single project I've worked on where coding standards made a bit of difference. Poor programmers will write lame code that complies with the coding standards, while great programmers will write great code that complies with the coding standards. Pissed-off, alienated programmers can obnoxiously comply with coding standards by writing incomprehensible and fragile code.

    I personally like to write software that someone, somewhere, will actually use. How do coding standards actually help that problem?

    My own experience has been that detailed coding standards tend to correlate with projects and products that go wildly out of control. My hypothesis on why that happens is that people involved in such projects all subconsciously know that and are desperately trying to control at least some aspect of the product development process. (one of my favorite's was a brief stint at a large, heartless company that makes large aircraft in a somewhat rainy part of America -- "all C functions must return a value, and all function return values must be checked". 'nuff said)

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

    1. Re:Coding standards depend on the ecosystem by sohp · · Score: 1

      I once got a look at a C program with a bunch of #defines used to make it look like PASCAL.

      #define begin {
      #define end. }

      Yah, that was a nightmare.

    2. Re:Coding standards depend on the ecosystem by Shados · · Score: 1

      Hahaha ouch, thats bad. I've seen some using #define to turn C++ programs in french. That was fairly awful too (fortunately curly brace languages aren't too verbose...)

      The worse remains all the people who use unicode languages to their "full potentials". When someone asks for help with a Java or .NET program on a forum, and paste you their code, and its written using Kanji....not many people can help =P

  34. If you're using Java, it's simple. by Anonymous Coward · · Score: 0

    Buy a copy of Triemax Jalopy, create a policy, then hook it up to your source code repository so that when developers check in their code, it automatically formats it.

    Problem solved. Everyone's code looks the same.

  35. those who cannot do, write coding standards by Anonymous Coward · · Score: 1, Insightful

    Some coding standards can be useful to enforce consistency in variable naming conventions, for instance. But if the document is lengthy and burdensome (with version history meticulously displayed at the beginning of the MS Word doc), and is meant to be kept handy during code reviews, that's often a sign that whoever prepared it is overmatched for the senior-level job they were originally assigned to. I've noticed this at several companies where I've worked.

    Consider letting the coding standards writer go during the next round of layoffs.

  36. 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 Shados · · Score: 1

      Your point is quite interesting in that it shows exactly why coding standards are important.

      Any -good- developer with -common sense- wouldn't need them: As long as what you write is sensible, readable, easy to maintain...who cares how you did it. The catch is, good devs with common sense are far and few in between, and they don't have a label. You can't tell someone "You do whatever you wish, I trust you!", and tell the guy right next to him "You have to do things THIS way!". So at some point you need to cater to the lowest common denominator.

      Some of the rules will get in the way of the good devs, but its a small price to pay to prevent damage from being done by the other type. If it was easy to have an intelligent conversation with -all- devs during code review, things would be fine... and in many smaller teams, it IS possible... otherwise, you end up like where my fiancee work: she's always cursing because, with 150+ C++ devs all going their own way, when you have to debug someone else's code, it gets.... "interesting", so to speak.

    2. Re:My workplaces' lovely standards... by Anonymous Coward · · Score: 0

      Why do your variables that store units not have the units as part of their type?

      Instead of using a float to store Hz or MHz, why not use a hertz and a megahertz class?

    3. Re:My workplaces' lovely standards... by StrawberryFrog · · Score: 1

      That do{ ... } while(0); thing is horrible, it's taking bad code and making it worse, not better.

      I recently argued against the "single return statement" rule over here.

      --

      My Karma: ran over your Dogma
      StrawberryFrog

    4. 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
    5. Re:My workplaces' lovely standards... by Anonymous Coward · · Score: 0

      Congratulations, that thing with the do {...} while(0) is the weirdest code idiom I've encountered in quite a while.

    6. Re:My workplaces' lovely standards... by Yosho · · Score: 1

      Instead of using a float to store Hz or MHz, why not use a hertz and a megahertz class?

      Because native types are faster than classes, and the stuff I work on is very performance-intensive. All those functions for setting, getting, and converting between types add up.

      --
      Karma: Terrifying (mostly affected by atrocities you've committed)
    7. Re:My workplaces' lovely standards... by Jaime2 · · Score: 1

      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.

      So you invented "finally". I'm not trying to pick on you, just pointing out that this is very useful and used in several popular languages. This turns out to be a good example of what I read elsewhere in this thread that what is good practice in one language might not be relevant in another. Java and C# both support a finally section of the try block which does exactly what you just described at the block level instead of at the function level. So, if cleanup is the justification for the "one return" rule, then it is truely useless and inappropriate in C#.

    8. Re:My workplaces' lovely standards... by johanatan · · Score: 1

      The 'do/while(0)' idea is completely idiotic. I am glad I do not work with those people. It is structurally identical to multiple returns yet with unnecessary clutter syntax around it. It's the same level of difficulty debugging either and I would bet the same assembly code is produced in both cases.

    9. Re:My workplaces' lovely standards... by scotch · · Score: 1

      Instead of using a float to store Hz or MHz, why not use a hertz and a megahertz class?

      Because native types are faster than classes, and the stuff I work on is very performance-intensive. All those functions for setting, getting, and converting between types add up.

      Depends on the language and compiler and optimization settings.

      --
      XML causes global warming.
    10. Re:My workplaces' lovely standards... by Anonymous+Brave+Guy · · Score: 1

      If you are using a language with lots of non-local gotos (or, 'exceptions' as they are now known)

      Non-local gotos and exceptions are not the same thing.

      Exceptions have been called exceptions for several decades.

      Nice try at sounding clever, though.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    11. Re:My workplaces' lovely standards... by Anonymous+Brave+Guy · · Score: 1

      Yep, the ol' infinite-loop-with-break trick is a classic way to avoid multiple returns without really avoiding them at all. See also "try {} catch (everything) {}" around the top level of a program to avoid having to deal with exceptions properly.

      What saddens me is the number of places that still don't allow things like break and continue, so you have to mess around checking all kinds of flags awkwardly in your loop logic. A related horror is not allowing early returns right at the start of a block, substituting nineteen levels of nested-if logic with no else conditions instead.

      Oh, and don't even mention trying to do a switch-case thing in Perl. }:-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    12. Re:My workplaces' lovely standards... by johanatan · · Score: 1

      I actually don't have a problem with catch everything--it allows you to format the error message for the user and to gracefully die instead of leaking exceptions. And, I think that both Java and C# will essentially force you to have the catch-all as even innocuous-looking statements in your main can throw underlying framework exceptions (and in the case of C#, asynchronous exceptions can pop in from any thread at any time--really annoying).

      Of course, I think the catch-all should be used in conjunction with proper context-sensitive catches throughout your program with exception specificities essentially being proportional to the depth in the call graph where they are caught--the outer catch-all catches the most generic type of exception whereas catches near the lowest level are most specific (and likewise all shades in between).

    13. Re:My workplaces' lovely standards... by epine · · Score: 1

      It depends on how you learned to reason about your code. If you learned to reason algebraically, boolean variables are an asset, not an annoyance. If you fundamentally think about your code as a sequence of events in time, break statements are a mental convenience.

      In my case, messing around with boolean often results in finding a more succinct or fundamental expression of the algorithm. No break statement has ever improved my grasp of an algorithm.

    14. Re:My workplaces' lovely standards... by mgiuca · · Score: 1

      Having a single exit point can make a function easier to debug. Not using GDB, but when you're eye-hunting for bugs - if you have return statements all throughout the code, you have to trace through to see the various exit points and figure out all the possible different return states.

      Having said that, I don't deliberately write code with one exit point. It's just something you have to look out for while debugging. IMHO if you code around it, then you're crapping up your code just to make debugging slightly easier.

      What you describe your co-workers doing is *extreme* crapping up of code. It's completely retarded. They still have lots of exit points; it's just that they're called "break" now instead of "return".

      Sounds like a case of hearing somewhere that "having a single exit point makes your code easier to debug", and so just blindly writing a single exit point in every function, without thinking about what it's really doing to the code.

    15. Re:My workplaces' lovely standards... by edsousa · · Score: 1

      So, the reason for single returns is that? I would expect 2 things:
      1st: cleanup code should be placed in destructors.
      2nd: a function shouldn't need cleanup code, it should do only what is meant to do and revert any side efects to the global state.
      By the way, let me introduce you to aspect-oriented programming, were the transversal requisites to your program have an identity and are separated from other code. Read more for example in http://www.eclipse.org/aspectj
      There is for C/C++ also. :P Google for AspectC++

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

    1. Re:Coding styles useless without enforcement by Shados · · Score: 1

      in 2008, there are many, many tools to check code standards. I don't know if the particular language you guys use has one...but code review time is valuable, and shouldn't be wasted specifically on stuff like that, when a check-in policy with a checker tool can do the job just fine, IMO.

      That said, I agree that code reviews are invaluable... else there's too much that shitty devs will get away with.

    2. Re:Coding styles useless without enforcement by dkleinsc · · Score: 1

      The value of code reviews isn't enforcing standards, although that's darn valuable.

      The real value of code reviews is that it forces the developer to defend the zillions of decisions they made when creating the code. The developer who knows he'll have to defend his work is going to spend more time thinking about design and writing clear code.

      Plus I've seen developers (myself included) pick up lots of good ideas by taking the time to review someone else's code.

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
    3. Re:Coding styles useless without enforcement by Pedrito · · Score: 1

      The real value of code reviews is that it forces the developer to defend the zillions of decisions they made when creating the code. The developer who knows he'll have to defend his work is going to spend more time thinking about design and writing clear code.

      And if the post had been about enforcing good code development, versus coding syles, I still would have brought up code reviews. But the post was about coding styles, which is why I pointed out the value of code reviews as they related to coding styles.

  38. Google C++ Style Guide by asserted · · Score: 1

    FYI, here's what it's like at Google: Google C++ Style Guide

    1. Re:Google C++ Style Guide by IamTheRealMike · · Score: 1

      The Google style guide is generally pretty good, but the 80 character limit is something I wouldn't adopt if writing my own guide. It invariably forces breaking the line in weird places, meaning you can no longer easily use indentation of lines to glance structure out of the code. It leads to a lot of redundant work if you don't notice you went over the limit and reviewers make you go back and fix it. The rationale is so you can view lots of files side by side or in xterms, but IMHO the uglifying effect on the code is enormous. The other thing I'm not so keen on is the tails to indicate private members. I don't tend to find that helpful, but I guess some people do. And finally minimizing use of vertical whitespace tends to result in quite hard to read and intimidatingly dense blocks of code, but again, I can see the rationale for having as much code on screen as possible.

    2. Re:Google C++ Style Guide by TheRaven64 · · Score: 1
      The 80 character limit is in place because that is how wide terms used to be, but the thing people miss is that terms are that wide because it's close to the maximum length of a line the human eye can easily track. For maximum readability, you want lines 66 letters long (which is 80 columns with some indent and trailing space). Any longer, and it's hard to jump from the end of one line to the start of the next visually.

      The problem with the Google coding standards is that they mix this rule (which makes sense) with putting braces on the end of lines, which means you have no clear way of knowing whether indenting is due to wrapping or a new block without actually reading the code.

      --
      I am TheRaven on Soylent News
  39. Some we used. by Javagator · · Score: 1

    A lot of coding standards are mostly personal preference, like indenting x spaces. Here are some for C++ that I think make your code less error prone.

    * Allocate resources in constructors, deallocate them in destructors.

    * Put objects on the stack, whenever possible.

    * If it does not make sense to copy or assign an object, then disable the copy constructor and assignment operator by declaring them, and not implementing them.

    * Declare and initialize objects as close as possible to where they are used.

    1. Re:Some we used. by Courageous · · Score: 1

      Declare and initialize objects as close as possible to where they are used. ...which has virtual, as does putting them all in one place, where one knows to look for them. Or, thinking of it another way:

      This part of the method is for allocating resources, this part for logic.

      C//

  40. Unmaintainable Code by eealex · · Score: 1

    I would highly recommend this article http://www.freevbcode.com/ShowCode.Asp?ID=2547/ enough for fun. but probably some people are already doing some of them in their code?

  41. 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
    1. Re:Style != substance by Fastolfe · · Score: 1

      So the problem with accessing the data members directly is that the author has forever limited his implementation to a hash reference. If he decides in later versions that it would be more efficient if it were implemented some other way, he can't do that, because his API assumes it's a hash reference.

      The second approach is preferred for that reason, and a (better?) Perl implementation could actually optimize it away to behave exactly like the first case, at least in theory.

      All languages have this issue. Many can expose their data members publicly, but there's always the chance that some setter/getter is going to be desirable in the future because you might want to do some filtering or transformation. And then you're stuck being unable to do that without totally rewriting the API and breaking everything.

    2. Re:Style != substance by melonman · · Score: 1

      In this case, it seems to me that the ideal solution would be lisp-style macros that would rewrite the getter/setter as a nested hash reference at compile time. Then you get a clean interface with no overheads.

      --
      Virtually serving coffee
    3. Re:Style != substance by gbjbaanb · · Score: 1

      From my experience, implementations never change. In the big world of large software projects, changing the implementation would introduce so much regression testing its not worth it. Instead, a ImplementationEx gets written and used in the places where its needed.

      So direct access of member variables isn't so bad a thing as you may think, though the reasons for using them aren't as important as their proponents think either!

  42. My thoughts by the100rabh · · Score: 0

    There are tons of coding standards, but the fact is when you writing code, it becomes a real pain to follow everything to the dot. I sometimes feel that just three things are followed(in no particular order, all are equally important), that enough.

    1. Write simple code, no cryptic code(Though sometimes for optimised code this might be not all that simple)
    2. Write small functions. Anything more than 50 lines is better moved to a function(Making functions inline makes sense sometimes)
    3. Give variables and function better, self explanatory names than i, j, temp,test etc. Give specific names(like rowCounter, loopIterator etc) , instead of generic names(like i, Counter, tempNode).

    1. Re:My thoughts by Anonymous Coward · · Score: 1

      Modify your last statement to:
      never use i j k ... for anything other than loop counters. i j k ... are standard, almost like a keyword

    2. Re:My thoughts by Anonymous Coward · · Score: 0

      Modify your last statement to:
      never use i j k ... for anything other than loop counters. i j k ... are standard, almost like a keyword

      Fortran lives! One of my personal rules is to never use these - identify the thing being counted in the loop instead, like "lineNo". You'll appreciate it when you have nested loops.

      The previous poster's #3 - Naming is perhaps the most crucial thing of all. Clear and consistent names!

      Also define types for things that are semantically different. We mix a lot of character sets (sadly) in our code and more often than not they're all defined as UINT16, WORD, unsigned short, w_char, etc.. I define TUCS2 for those characters and, say TSJIS for another. That way it's perfectly clear what a function expects. They might be all a 16-bit word underneath, but it sure makes the code easier to read (and change!).

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

    1. Re:A few anti-guidelines by soccerisgod · · Score: 1

      Does it really matter what your DELPHI code looks like? I'd think if you used that all hope was lost anyway :)

      --
      If a train station is a place where a train stops, what's a workstation?
  44. 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.

    1. Re:Editing the minimum # of lines possible by YodaYid · · Score: 1

      I disagree - I think that there can be good reasons to only change the bare minimum. If you have a mission-critical, *working* program, reliability and stability are more important than efficiency or elegance. So your nested-if's example looks silly, but at least it works :-)

    2. Re:Editing the minimum # of lines possible by MobyDisk · · Score: 1

      You aren't disagreeing. I didn't say that there was no case where this approach isn't valid. It just isn't a good idea to do for 10 years straight without ever stepping back and looking at what the code actually does :)

      If you are doing a hotfix to production code that is going to have minimal QA time, then yeah, do the minimum change.

      In this particular case that I described, nobody wanted to make the change. None of the other developers could document what the code did or could tell if it met the specs. It was constantly changing and constantly wrong.

    3. Re:Editing the minimum # of lines possible by vaz01 · · Score: 1

      If a firm is that afraid of changing anything about their code for fear of the whole thing collapsing, then they must not know anything about testing code, which means they pretty much don't have any business making it in the first place.

  45. MISRA Guidelines by NeuralAbyss · · Score: 1

    The MISRA software development guidelines for C can make a lot of sense in embedded, real-time or safety-critical systems, and can also be applicable outside of that application domain.

    On the whole though.. one thing that tends to be lacking in coding standards is an underlying reason behind many rules - it's hard for developers to judge the applicability of an exception if they don't know why the standard was introduced - common error? Past internal experience?

  46. FDA regulated environment by Anonymous Coward · · Score: 0

    And we have files that run 8k lines, they're unintelligible and almost impossible to maintain.

  47. Let developers work how they want by WPIDalamar · · Score: 1, Insightful

    As far as formatting goes, I believe in letting each developer do it however they like. Things like braces on the same line, or on the next line just don't matter that much in a world of automatic code formatting utilities.

    I just wish there was a way to view code in your preferred style, but not actually modify it.

    1. Re:Let developers work how they want by careysb · · Score: 1

      I just wish there was a way to view code in your preferred style, but not actually modify it.

      Here, here. Listen up tool developers!

  48. braces and line lengths by fragbait · · Score: 1

    Good (personal preference, rather):

    - braces on separate lines
    - white space after parenthesis
    - white space between operators
    - white space after commas
    - white space between ideas

    if( something == something_else )
    {
          arg1 = argx + argn;
          idea1( arg1, arg2, arg3 );

          argz = argy + argg;
          idea2( argz );
    }

    My reasoning for this is legibility. I find that those that don't do this tend to write "wall-o-text" code, e.g.

    if(something==something_else){
          arg1=argx+argn;
          idea1(arg1,arg2,arg3);
          argz=argy+argg;
          idea2(argz);
    }

    I just think the white space makes the code easier to read, especially in the absence of comments or function/variable naming standards. Think of the ideas like paragraphs.

    Another two good ones are all caps on CONSTANTS and constants on the left of a comparison, e.g. CONSTANT == var, to catch any assignment typos.

    Bad (or silly):

    - line length restrictions

    I've just never found this one useful. Usually, the reason for it is for printing, more so for older printers that would truncate past 80 characters.

      - endless( arg1 ).calls( arg2 ).strung( arg3 ).together( arg4 ).off( arg5 ).a( arg6 ).variable();

    I'm on the fence on this one. Sure, I see the value of less lines, but wow it is hard to get the idea out, especially in the absence of comments.

    I think these questions on slashdot are like hoping your 1000 monkeys will eventually create Shakespeare. I hope you like reading.....

    -fragbait

    1. Re:braces and line lengths by Shados · · Score: 1

      For code style standards, the important part is really that its followed and consistant, more than what you actually do. For example, in .NET, it is against the standard framework design guideline to use all caps for constants, which can really mess people up if its put in a public librairy: all your code use a standard, EXCEPT for the parts where you need to use the third party constants, which end up standing out over the rest because they're screaming caps.

      Others, like line length, will seriously depend on your work environment. I'd say if you have a decent size team, you'll need one, but make it large (not 80 characters or something silly like that), else SOMEONE will have a 2000 character line somewhere (I've seen it...ugh...). There's always the bozo who wants to make his code short by putting an IF statement on a single line, and is too lazy to import namespaces, so ends up qualifying -everything-... so you end up having to scroll horizontally even if you have your IDE stretched out over 3 monitors. Of course, if 80% of your team is working in Emacs over a small window through SSH on a server, it may be a good idea to make it shorter (I don't know why they'd to that, but I've seen such teams...and at that point if they're not going to change, you may as well make the team more efficient by restricting it).

      In the end, its all about making your team more efficient and your code better :)

    2. Re:braces and line lengths by Whoever · · Score: 0

      I am definitely in the "braces get their own lines" camp. Nice to see someone on this thread holding down the fort.
      I struggle to understand why more programmers do not do this.... it makes the code so much easier to process (at least with my brain)

      http://bellspace.net/

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

    1. Re:Standards are important for shared projects by Anonymous Coward · · Score: 0

      So if we don't agree with you, then we are too selfish to work on a multi-person project and probably live in our parents' basement.

      Hoo-kay...

    2. Re:Standards are important for shared projects by Anonymous Coward · · Score: 0

      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.

      Statements like this make me very happy I have left the corporate world to go back to academia.

  50. 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]
  51. [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

    1. Re:[C#] Use FxCop, StyleCop, Resharper by lalena · · Score: 1

      I agree. OOur biggest problem is that we started with VS2003, so we couldn't have FxCop warnings appear as errors, and without doing that things can get out of hand quickly.

  52. Use any established standard by shutdown+-p+now · · Score: 1
    The best bet is always to pick a well-established existing standard for the language/platform you use, and stick to it, no matter what your personal preferences are. The reasons are simple: first, other programmers are likely to do the same, and second, third-party code you're going to use will likely be written using that style as well.

    This is particularly true of Java and C#, where language/platform creators have established a standard themselves. Though I've noticed that Sun's Java coding guidelines seem to be more closely followed than Microsoft's C# guidelines, particularly with regard to the placing of curly braces (but then again, Microsoft themselves don't follow their naming and bracing guidelines, as anyone who looked at the .NET source code quickly found out).

    For C++, this is trickier - you have several indentation/bracing standards, and also camelCasing/PascalCasing/separate_with_underscores. Sometimes it's a no-brainer - if you mostly use Qt, then just follow its style. But for projects that use many different third-party libraries (or the opposite - when few/no third-party code is used), you'll have to pick something. Personally, I've found Java-style naming to be the most convenient (PascalCasing for class names, camelCasing for variables and functions, ALL_CAPS_WITH_UNDERSCORES for constants), though I still prefer ANSI C indentation and bracing (braces on separate lines, not indented to the level of their content).

    1. Re:Use any established standard by Shados · · Score: 1

      hahaha, you wrote almost the same thing I did in another post, so while scanning comments, I thought I was reading my own :)

      By the way, about C#... one reason the guidelines aren't followed much, is that A) a lot of C# devs are code monkeys and don't even KNOW they -exist- (ex-VB6 devs, for example), and B) some aren't defined.

      There isn't an official guideline for braces in C# in the framework design guidelines. Recently, Microsoft released their C# coding standard recommendation (which isn't the same thing as the design guidelines, which, for example, rules on the naming conventions), but it isn't a strict recommendation like the FDG. Also to add to the confusion, at the end of the official design guideline book, there is a C# guideline recommendation (which isn't part of the official spec), and it was made by the author. Ironically, it does -not- follow the more commonly used standards, and isn't the same at all as the actual microsoft recommendations... So obviously, with that, no one's going to know what the heck they have to follow beyond whats in FDG.

      The .NET framework actually follows the design guideline on the dot. The catch is, the design guideline ONLY applies to public APIs. (So public classes and methods, etc). The source style rules are the one that apply to the private stuff, but those are more recent, so of course the older .NET code won't all follow it.

    2. Re:Use any established standard by Bloater · · Score: 1

      separate_with_underscores

      In case you're interested, this is called snake case

  53. One of the worse: Iinterface by smartin · · Score: 1

    One of my pet peeves is people prefixing Interface names it 'I'. This exposes an implementation detail to the user of the Object that it should not and makes it difficult to refactor.

    Another horrendous one is hungarian notation, this should be explicitly banned and punished.

    --
    The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
    1. 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

    2. Re:One of the worse: Iinterface by smartin · · Score: 1

      A common progression from my experience is something may begin life as an object, then become an abstract object and finally an interface as the code develops.

      --
      The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
    3. Re:One of the worse: Iinterface by StrawberryFrog · · Score: 1

      Yup, that's pretty much what I said. Interfaces tend to come out from classes. Not vice versa.

      --

      My Karma: ran over your Dogma
      StrawberryFrog

    4. Re:One of the worse: Iinterface by cswiii · · Score: 1

      Refactor how, and how often do you do this? Reply under this comment [slashdot.org], please.

      Would that be a GOTO? ;)

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

    1. Re:Formatting vs coding practices by Anonymous Coward · · Score: 0

      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.

      Not to troll or anything, I seriously never understood why you would prefer spaces to tabs. It's not like I am doing ASCII art in my source files and for indentation the concept of indenting lines at virtual tabular cells seems reasonable. A lot of people are very vocal about this but I never found any good explanation.

    2. Re:Formatting vs coding practices by PPH · · Score: 1

      And if you do get someone to explain it, could you get an opinion on the toilet seat up/toilet seat down controversy as well?

      --
      Have gnu, will travel.
    3. Re:Formatting vs coding practices by Twylite · · Score: 1

      Because in a fixed pitch font editor a space is always exactly one character wide, but the width of a tab is variable.

      I work in an environment where we maintain a LOT of software and firmware bits across a large number of languages and dev environments. We have a couple of projects where the majority of the code base compiles under Visual C, gcc (linux), cc (solaris), and two different embedded compilers.

      If you are working on Windows (which most of us do) you will usually edit in the MS Visual C IDE, but sometimes you'll need to use one of the embedded IDEs for debugging. On Solaris we use vi and gdb, and on Linux we use whatever is the nicest thing on the distro we are debugging on (we target 4 different distros).

      A space is a space. A tab is different in every IDE/editor. Using spaces instead of tabs is about the only style rule we have in our practice manual.

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
  55. 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).

  56. 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.
    1. Re:Languages, tools, and libraries by Anonymous Coward · · Score: 0

      When concatenating two strings, if it's important to preserve the entire contents, use a string class such as std::string. Otherwise, use strncat() to avoid a buffer overflow.

      strcat() should be avoided unless it is known in advance that the result will fit in the supplied buffer. In fact, this type of coding mistake is responsible for many security alerts on Windows, Linux, etc. Catching these bugs during coding reviews is important, but a sweep of the entire source code base using shell scripts or other automated tools is essential.

    2. Re:Languages, tools, and libraries by Darth+Android · · Score: 1

      That code is *not* easier to understand. I glanced at your post and thought "first bitwise XOR second", as that statement would mean in most major languages. Even VB's & operator, while slightly better (first AND second at least sounds like concatenation), still flags as a bitwise operator until I look at the code closer. I'd say the + operator makes the most sense for concatenation because the concept of adding two strings together makes logical sense.

      --
      Do not meddle in the affairs of dragons for you are cruchy and good with ketchup.
    3. Re:Languages, tools, and libraries by RAMMS+EIN · · Score: 1

      ``That code is *not* easier to understand. I glanced at your post and thought "first bitwise XOR second"''

      I understand where you are coming from, but really, what you're saying is a red herring. Had you known OCaml, it would have been immediately obvious to you what the code did. I considered for a while to use some hypothetical OCamll string concatenation function to prevent people from getting confused like you did, but, in the end, decided against it, because, in OCaml, you would just use the ^ operator. Anyway, as I said in my previous post, the fact that OCaml has an operator for string concatenation is besides the point.

      The point is that the way OCaml handles strings allows string concatenation to be expressed succinctly and clearly, whereas, in C, one has to jump through hoops to get it right. This is where the programming language has an influence on the readability of the code. No matter how hard you complain about ^ not being the right symbol for string concatenation, the fact stands that in C, it cannot be expressed that clearly. You need some boilerplate code to do memory managment and check that you are actually passed strings and not NULLs. So, even if you know C, you will have to look at a couple of lines of code, until you figure out that what it actually means is "concatenate the strings first and second".

      If it makes it easier for you to understand, feel free to imagine a hypothetical "strcat" function in OCaml, or an hypothetical language that is exactly like OCaml but uses whatever operator you prefer for string concatenation.

      --
      Please correct me if I got my facts wrong.
    4. Re:Languages, tools, and libraries by Smork · · Score: 1

      While I agree with the general spirit of your post, please allow me to introduce you to a magic function called 'asprintf'!

      'man 3 asprintf' says:

      "The functions asprintf() and vasprintf() are analogs of sprintf(3) and vsprintf(3), except that they allocate a string large enough to hold the
      output including the terminating null byte, and return a pointer to it via the first parameter. This pointer should be passed to free(3) to
      release the allocated storage when it is no longer needed."

      So your very long example just became a bit shorter. Of course you need to check if the returned string != NULL (just in case there wasn't enough memory). You also gain all the nice formatting functions of printf (though "%s%s" will do nicely in your example).

  57. Coding rules are not about presentation style by Anonymous Coward · · Score: 1, Informative

    If you are working for a compagny which pretends engineering software and which starts by giving you a coding rules guide of one hundred pages long which speaks only of indenting and whether or not to uppercase function names regarding their scoope or how to format function name prefixes regarding the supposed module they belong to, then RUN AWAY ! (1)
    There are plenty of utilities which are able to automatically do all that typo job for you.

    Do not confuse coding rules and presentation style, coding rules focus on adding formal information about symbols or instruction blocks which are not already implied by the semantic of the used programming languange.

    For instance, in C, if you use macros which are a substitute for inline functions, then it is good to provide a prototype for the implicit function and a syntactic tag which explicit the way the macro will be used within the macro definition.
    This way, a home-made static code analyser is less likely to get confused by macro-which-looks-like-functions.
    Once such formal information is put whithin your code, any serious text editor will be able to reformat and to present it the way you like most.
    And such way of presenting code can be different regarding that you are currently writting it or that you are an integrator who have to merge two versions of a file or that you are reviewing someting written by one of your coworker or again that you are rewriting a piece of code you wrote some monthes ago, etc.

    Continuing on C, what kind of macros will you allow to be used, only constant definitions? Inline functions replacement?
    More complicated: if you use critical sections over data or code, what kind of information do you add to let a tool verify that you do not jump out of your section without realising it?

    Presentation style can be usefull, but coding rules are about making a link with the design and test plan constraints and requirements.

    If, in a software compagny, people debate on presentation indents and typo rather than on formatting tools and static analysers, well, they just don't get it, or more precisely they lack the competence and the talent to formalize the relatio n between the information they would like to be presented within the code and the semantic of this information. In this case, you will see presentation style changing regarding who is in charge of deciding it, regarding the current coding fashion of the moment, while the base coders will still being complaining of doing the same thing year after year, hitting the same kind of problems on the same kind of code, and that they expect code reviewing to be about the semantic of their code and not about typo.

    (1) well, I guess it depends on how much you are paid, after all ;)

    1. Re:Coding rules are not about presentation style by Anonymous Coward · · Score: 0

      I agree with you, one of my tasks right now is write a coding style document for new developers that join the company and the only examples that my superiors suggest is presentation style rules, i really hate discussions about indent style. There are examples of well made coding style documents?, how this topic should be presented to you, so you don't run away from a company?.

  58. 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(_).
    1. Re:no multiple return statements? by Tony+Hoyle · · Score: 1

      Maintainability. If you return from multiple points then you can make a simple 'make the function do foo before it returns' to 'edit two dozen return statements to do foo before it returns, oops missed one.. difficult to find bug alert!'.

      That said, if the function is small there's not a major problem with it. I'd LART that function based on the 100s of lines of code not the return - if you have 100s of lines of code inside a code block break it out into a function, so you actually have a hope in hell of reading the program flow.

    2. Re:no multiple return statements? by StrawberryFrog · · Score: 1

      Why would anyone decide that return statements were off-limits? I don't know, but some people do.

      I don't think it's a valid rule. there is a longer discussion of the topic here

      --

      My Karma: ran over your Dogma
      StrawberryFrog

    3. Re:no multiple return statements? by StrawberryFrog · · Score: 1

      make the function do foo before it returns

      That's exactly what try...finally blocks are for. See here.

      --

      My Karma: ran over your Dogma
      StrawberryFrog

    4. Re:no multiple return statements? by dysfunct · · Score: 1

      Ah thanks, didn't think about doing something before returning. I must admit this is a valid argument. On the other hand, I don't think that this rule should be set in stone in any practical coding standard. I've seen way too much code where a simple early return statement could have prevented insanely deep nesting which makes the code hard to understand, especially with inexperienced programmers who don't know how to simplify the logic.

      I also absolutely agree with you on the point of breaking code out into a function. It's just that the proper solution is unlikely to be the one you encounter in real-life projects. *sigh*

      --
      :/- spoon(_).
    5. Re:no multiple return statements? by oldhack · · Score: 1

      This was a practice from "structured" design, the predecessor to OO paradigm. GOTO was the major villain back then, and this practice ensures the control flow goes down one single direction, instead of jumping off/out at arbitrary points.

      Still a good practice, in my opinion, but like everything, gotta apply your judgement.

      --
      Fuck systemd. Fuck Redhat. Fuck Soylent, too. Wait, scratch the last one.
    6. Re:no multiple return statements? by Anonymous Coward · · Score: 0

      In Java, you could always use a "finally" statement. That said, I could see the point in trying to keep the number of return statements low but enforcing a single return statement seems a bit much so long as your functions or methods aren't longer than they should be. I suppose it depends on the field but in my years of coding, coming back later to insert is a very rare thing; if it's rare for whatever group you're working with, then changing code structure to fit that rare occasion seems unnecessary and perhaps the awkwardness will hurt the code in other ways.

    7. Re:no multiple return statements? by dkf · · Score: 1

      I've seen way too much code where a simple early return statement could have prevented insanely deep nesting which makes the code hard to understand, especially with inexperienced programmers who don't know how to simplify the logic.

      That's an important observation that I've seen in a few places, and which also jibes with my experience. Whatever the length of your code, deeply nested code is bad news; it's much much harder to read than something that's functionally equivalent but shallow.

      It doesn't help that most of that sort of deeply nested code tends to have lots of different flag variables all over the place to manage the redirection of the control flow from one deeply nested location to another. What the authors of such horrors have done is recreated spaghetti code using structured programming, but with even more complexity than the version with multiple exit points. Doesn't look like an overall win to me.

      In my experience, good functions have conceptual integrity (they do one thing and do it properly) and are structured into four parts: checking preconditions, performing the changes, and cleaning up. The fourth part is a comment (usually at the front of the function) describing the intention of the function and its post-conditions. Early exit from the precondition check part is fine (though can require some cleanup sometimes) but once you start doing the real work, exit should only be through the cleanup part. The real work part should be as short as possible, but it's not as critical to keep the precondition checks short. (Cleanup length is usually not an issue; if it is, it probably needs factoring.)

      The other really useful guideline I've seen is "be consistent and informative in variable name usage". It doesn't matter what the names are (except for 'i' and 'j', which had better be iterated indices) as long as they're consistently used; the goal is to make the code easier to understand at a glance.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    8. Re:no multiple return statements? by Anonymous Coward · · Score: 0

      Why not just return immediately if any basic conditions or assumptions are not met and prevent that completely unnecessary indentation?

      I believe that this would actually be a remnant from stuff like C or assembler-coding, where you'd quite frequently need to cleanup stuff you had going on in your functions manually. Combine that with error handling, and you'd frequently see the advantage of avoiding multiple returns.

      More modern programming languages typically handle cleanup of memory allocation etc in a much more programmer-friendly (although granted not always as efficient) way, so to me the need isn't really there for these kind of guidelines in Java etc...

    9. Re:no multiple return statements? by Twylite · · Score: 1

      In C or asm you jump to a cleanup block at the end of the function using goto.

      Many developers use a deeply nested if/else structure to accomplish the same thing (with much less clarity) because everyone knows that goto is harmful ... right?

      Everyone also knows that an if() must have an if-not branch (also known as "else") to be "complete".

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
  59. Which only look good on paper? by Panaqqa · · Score: 1

    That's easy... object oriented

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

  61. Bikeshed by ezzzD55J · · Score: 1

    I've tagged the article bikeshed. It's one of those subjects everyone can have an opinion of that matters little. IMHO.

    1. Re:Bikeshed by try_anything · · Score: 1

      It isn't an intrinsically "bikeshed" problem. There are things of value to be said about it and legitimate points to be argued.

      To pick a simple example, when you add code to a project, you should conform to the standards that are followed in that project: naming conventions, indentation standards, documentation standards, error handling conventions, logging formats, everything. It's a no-brainer, but it's worth repeating because there are so many people who just don't get it.

  62. Some real advice by bokmann · · Score: 1

    Key points:

    There is no 'one size fits all'. It depends on the language, the corporate culture, and even the kind of app you might be writing.

    A coding standard is necessary for teams of any reasonable size - even though people will complain about them, chances are if the team is that large, the code will be maintained for 'generations' of developers. You need to optimize for the poor sod a year from now who has to understand what this code is doing, not optimize for the guy today who wants to be clever.

    The coding standard should not be externally imposed by an organization that doesn't have to live with the decisions.

    The coding standard should evolve over time. Languages change - for example most coding standards I've seen for Java don't say 'boo' about the syntax changes introduced with generics or annotations.

    Here's how you achieve that:

    1) Start with a blank whiteboard
    2) get the team that will be writing the code together
    3) list everything you agree upon, get that out of the way
    4) list stuff you *mostly* agree on, and get dissenters on board, even if only for a 'trial' period.
    5) Every few weeks (perhaps corresponding with your retrospective at the end of an iteration), review what is working, what isn't and make changes.

    This way, the standards will evolve with the needs of the team, and people who dissent only have a few weeks before they get to try to sway people again, and learn to give up if the idea doesn't take hold.

    Respect people's pain when making these decisions. You might have strong opinions that conflict with someone else on your team - in the long run, it doesn't matter who is 'right', but the poor guy who is constantly trying to pull fixes up into a release branch might really be pissed off when the 'brace placement churn' causes him issues. He might not care *where* they are, just that they don't change every week.

    Issues that there are no good answers to:
    1) When you change your coding conventions, what heppens to all the code that follows the older conventions?

    2) If you are doing a lot with branching and merging in a version control tool, churning of the coding standard can create 'false diffs'. You'll want to minimize these while evolving the standard.

    So, don't try to come up with the perfect coding convention document, try to come up with the perfect mechanism by which your team can develop and evolve the conventions they need.

  63. 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 ]
  64. Horrible naming standards by OTDR · · Score: 1

    Our company provides, among other things, software engineering support to customers who themselves develop commercial products. In such cases we have to make our code as indistinguishable as possible from their own in-house code. One customer has a naming convention descended in ages past from the old Hungarian notation which makes for code that reads horribly. As example:

    pstFoo->fBar -- a pointer to a float (or double) 'Bar' in structure 'Foo', or

    dCALCOEFF -- a #define or a macro, (certainly not a double as the rest of their naming scheme might imply, and

    fnSomething() -- a function (like the parens don't give it away)

    Our philosophy is "name & format for maximum readability and let the compiler catch variable typing errors," which works well if you clean the code until it builds without warnings. These folks routinely build with dozens and dozens of "normal" warnings. Their entire "coding standard" is a case study in what not to do.

    1. Re:Horrible naming standards by Shados · · Score: 1

      the fn/fu prefix in front of functions drive me insane (especially in OOP, where its a freagin method, not a "function" anymore, so to speak). I've only seen it once, and thank god its a 3 month contract, but jesus... Even worse, in some part of the apps its done: FU_someMethodName(). That makes my eyes bleed.

      Then translate that in SQL, and add all upper case... USP_XYZ_GetSomeData, where XYZ is a 3 letter abbreviation of the application that uses the stored procedure (which of course forgets that one of the primary reasons to use stored procedures is to share the public API of your database model with multiple applications...)

  65. MISRA by Anonymous Coward · · Score: 0

    I work in a highly-regulated industry. We use the MISRA standard for C, and use an automated code analysis tool to find rule violations. This would probably be overkill for non-safety-critical applications, but might give you some ideas.

  66. Re:braces && 3 year olds by thogard · · Score: 1

    The test subjects could all count and they were subjected to an adding program that the all did very well with... until I pointed out that I though they were seeing 4+3 as find the 4 and count 1,2,,3 on the next keys. The pattern matching was done with a wide range of other subject matter including having them find quotes in Shakespearean plays. It appeared to me that they could judge how long a boring speech was and point out a proportionally long paragraph in a book if it was all on one page.

  67. Having one is more important than which one. by Anonymous Coward · · Score: 0

    Just having a set of standards in the first place is way more important than trying to decide which one is better.

    In fact, trying to get developers to agree on coding standards is an exercise in futility. You're better off having your development lead / architect make these decisions.

  68. Rather than... by swilde23 · · Score: 1

    .. asking a bunch of passionate amateurs, I usually go take the advice of someone I know has years of experience in the field and hopefully has editors that I can trust.
    http://www.amazon.com/Coding-Standards-Guidelines-Practices-Depth/dp/0321113586
    If both Herb and Andrei got it wrong, then I who am I to try and get it right?
    I suppose you didn't specify which language you are using. So it's possible that nothing in this book (or a similar book) will be valuable to you. However, I highly doubt that. Much of the advice is valuable cross-language. My advice would be to not worry about the small things that just annoy the programmers and make sure your standard covers the big, important ones.

    --
    There are 10 types of people in the world. Those that understand this sig, and those that beat up people who do.
  69. Good and Simplistic Requirement by Anonymous Coward · · Score: 0

    The maximum length of a line is around 100 characters (+ or - 5). Keeps code readable in many editors and shuns excessively complex statements.

  70. optimized version by Anonymous Coward · · Score: 0

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

  71. Our secrets.. by gru3hunt3r · · Score: 1

    Somebody earlier wrote about having subroutines which didn't fit on the screen. I agree, which is why all developers in our company use monitors which are tilted 90 degrees to fit more lines per screen. (Samsung makes some sweet high refresh models which swivel with no special mounts or anything)

    However breaking things into small subroutines isn't not always practical, you end up with far too many subroutines which are "dubious" in purpose and it *can* directly conflict with another writer who talked about good names for subroutines. One subroutine per page also conflicts with the black-box idea that each routine should *always* validate it's own data. Good validation can *and should* often take more than a page on it's own.

    To solve these seemingly contradictory mandates we've adopted a process of adding "sanity" lines which are large inline comment blocks which segment various parts of a subroutine.

    e.g.

    ################ SANITY ##################
    ## at this point the following is true:
    ##
    ## 1. all user supplied data has been validated.
    ## 2. the fuzzinator is true or $err is set.
    ## 3. all the arrays are initialized.
    ##
    ## now lets go for a ride.
    ##

    now .. it means that if i want to add validation data I put it ABOVE the sanity line, and below the sanity line I can implicitly trust any data.

    oh yeah, for this to work and only ONE return allowed per subroutine unless it is above the first sanity line... but in general every routine MUST exit at the bottom. so you end up with lots of

    if (not $err) { // do something ..
        if ($ohshit) { $err++ };
        }

    it's kind of complicated to explain this stuff, and I'll freely admit new guys hate it for the first 3 months. But once they get the hang of it then we've found it also reduces our error rate and the overall cost of lifecycle maintenance substantially.

    Last note: comments should *always* be fun, they can tell a story (this is a pro technique), they should (and routinely do) include swear words. Anything which would be non-obvious to a n00b c0der should be commented. All regular expressions should indicate WHY they exist (not what they are doing)

    BAD EXAMPLE:
    $foo =~ s/[^a-Z0-9]+//g; # strip non-alphanum chars

    GOOD EXAMPLE:
    $foo =~ s/[^a-Z0-9]+//g; # username must contain only alpha-num

    Finally -- and this is the most important: as I said earlier make sure your comments should be written to be fun for the reader: drop easter eggs, riddles, haikus, hide n' seek, baby games, user dialog (short plays), ren & stimpy dialog (stimpy you idiot!), pinky & brain dialog (what are we gonna do tonight brain), are all some of my favorites. Fun comments makes the next guy/gal much more likely to actually READ them --- and means their less likely to screw up the code which will result in more work for all of us. It also entertains managers who want to look over our shoulder and makes the qa team more likely to go look in the code so they can develop better test cases.

    1. Re:Our secrets.. by Anonymous Coward · · Score: 0

      1. Assertions are superior to "sanity" comments, although commented assertions are OK

      2. Swear words in comments or variables names should be avoided, unless maybe the project is a video game.

      3. I'm not crazy about riddles, haikus, and the other stuff you mentioned either. One easter egg for a large project (multi-person, multi-year, many confirmed customers) is OK. Otherwise developers start focusing on trivia which has nothing to do with the job.

      4. If managers need to be entertained by comments embedded in source code, they're in the wrong job. Although I admit, many managers I've worked with seem to be in the wrong job.

      5. I hope I don't get a chance to work for the company you're currently in.

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

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

    For one thing, they is grammatically plural.

    --MarkusQ

  73. It's not so much the guidelines... by digitig · · Score: 1

    ... as the process and the explanation. Every rule in the guidelines should be there for a reason, and the reason should be explained so that it's clear (and straightforward to justify) when you should breach the guidelines ("The customer won't pay us if we don't do this" is, of course, a perfectly valid reason, and may be the case in some heavily regulated industries). And the guidelines should not be set in stone -- if a rule causes more problems than it's meant to solve then it should be easy to get rid of it. It should probably be harder to get a rule put in, but it should be possible. Neither of those is practicable for major, published standards such as MISRA C, so you need local standards.

    I'm not sure it's meaningful to talk about coding standards in isolation, by the way. I consider it essential for serious development that the purpose of every function and its parameters be recorded, but whether that's done in a comment (in which case it belongs in the coding standards) or in external documentation (in which case it belongs in development standards) depends on the type of environment.

    --
    Quidnam Latine loqui modo coepi?
  74. Re: GOTO by TaoPhoenix · · Score: 1

    The only dabble in non-web programming I ever did was fiddle with Commodore Basic as a child. I suppose I was lucky enough to stumble upon one early article somewhere advising against the worst excesses of "Gordian-Sphagetti" code. I understood that as far as it went, and made some efforts to keep a simple enough main program and put the subroutines to the heavy work.

    However, I never did understand how to write an entire program without a GOTO statement, because depending upon certain condition checks, it became time to restart the program at some point in the process.

    The best I was able to manage was something like eight-ish GOTO statements per 1000 line programs.

    I'll be looking to write some tiny widgety programs in the future, and I don't see why having a few GOTO statements is the total kiss-of-the-ZombieCode. I have no interest in pro-level programming.

    --
    My first Journal Entry ever, in 8 years! http://slashdot.org/journal/365947/aphelion-scifi-fantasy-horror-poetry-webzine
  75. 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.

    1. Re:Multiple exit issues - bogus problem by Shados · · Score: 1

      Well, a lot of the issues come from a much simpler source: it confuses code reviewers.

      But in this day and age, there are a lot of tools which can highlight exits and give visual indication of their type (exceptions, returns, breaks...) and the problem really goes away...

    2. Re:Multiple exit issues - bogus problem by Anonymous Coward · · Score: 0

      The actual topological constraint is that backwards control paths must not cross.

      Are you sure? I have a place where either they must or the code doesn't work correctly (large FSA w/ hundreds of states implemented with GOTO logic for state).

      No, I'm not writing out the state transition table in a array[200][200]. gotos are far easier to maintain and run faster.

  76. Anyone else skipped parent comment .. by Anonymous Coward · · Score: 0

    .. after seeing 'Java' ? :)

    1. Re:Anyone else skipped parent comment .. by Lucas.Langa · · Score: 1

      That is the reason I used this tag as the first word ;)

      --
      Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
  77. It doesn't matter by Anonymous Coward · · Score: 0

    The truth is, it doesn't matter what the coding standards are. The sole value of coding standards is to make the code all be formatted the same. Any standard will do that.

    Code formatting gets a lot of people heated up in practice, but the amount of heat is disproportionate to the importance of the issue. The *code* is important; how the code is laid out isn't.

  78. From Herb Sutter's Book by Anonymous Coward · · Score: 0

    C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

    0. Don't sweat the small stuff. (Or: Know what not to standardize.)

    Say only what needs saying: Don't enforce personal tastes or obsolete practices.

    Any coding standard that does not self-regulate itself in this way is suspect. Nevertheless, there are still 101 good practices to enjoy. Buy the book.

    What is specifically left _out_ of the standard?
    Brace style, tabs/spaces arguments, which side of the equality operator to place non-const.

    All the stuff of stupidity and pettiness.

    Take a look at the MISRA-C for another coding standard. While I don't find MISRA-C all that compelling, at least it deals specifically with substantive choices (whether you agree with them or not is another matter).

  79. Yep, that's good old .. by apankrat · · Score: 1

    .. "no tabs in the middle of the line" rule. Especially relevant in multiple variable declarations:

    int{tab}a;
    long{tab}b;
    double{tab}c;

    --
    3.243F6A8885A308D313
  80. Indentation by Animats · · Score: 1

    Python people argue over tabs vs. spaces for indentation. In Python, where indentation matters, it's a major issue. Python implementations really ought to insist that a file have only leading tabs or leading spaces. Mixing of tabs and spaces is clearly wrong.

    A big UNIX design mistake was to have a tab equal eight spaces. If it had been four, everything would have worked out better, since four spaces is a reasonable indentation amount. It's eight because, when outputting to a Teletype Corporation 100-speed printer (ASR/KSR 35 or 38), the carriage can reliably move eight spaces in one character time. So, if you set the hardware tab stops every eight spaces on the printer, this provides maximum output speed. That's the real reason.

    For C and C++, just run the code through "astyle -style==ansi". Let the machine do the work.

  81. Dumb as coder by Anonymous Coward · · Score: 0

    Your function can be writen like this:

    int multiply(int a, int b)
    {
        return (a*b);
    }

    Wow ... look at that ... no C&P needed.

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

    1. 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!
  82. Wackier Style guidelines in my shop by Anonymous Coward · · Score: 0

    I work in a Python shop... Some of the odder rules:

    1. No more than 3 parens in a row.

    Eg, map(len, foo(bar(x))) is illegal.

    2. Set temporary variables to keep each code line simple. Eg:

    result = function1(function2(...), param, [list, of, stuff])

    becomes:
    temp = function2(...)
    temp2 = [list, of, stuff]
    result = function1(temp, param, temp2)

    3. Embedded SQ: put the starting keyword of each clause on its own line in a multiline string, eg
    sql = """
        select *
        from table
        where ...
        """

    4. Add line breaks to list comprehensions at the "for" and "if" clauses. Line up the "for" just after the opening bracket.

    settings = [line.strip()
                  for line in lines
                  if not line.startswith('#')]

  83. AGREE 100% by Anonymous Coward · · Score: 0

    The JSF coding standard is on of the best.

    BTW: The only reason dumb ass professors (most who have never worked outside of the educational field) teach students to put the opening brace at the end of a line is to save print space.

    There is nothing functional about having a hidden/hard to see/find opening brace. Braces are there to "wrap" the area of a control statement. If another person (developer or non-developer) spends more than 3 seconds trying to figure out where a control statement begins, then the developer FAILED to write maintainable code.

    1. Re:AGREE 100% by Peter+La+Casse · · Score: 1

      BTW: The only reason dumb ass professors (most who have never worked outside of the educational field) teach students to put the opening brace at the end of a line is to save print space.

      The more code I can fit on my screen, the better. An opening brace at the end of a line isn't hidden, hard to see or hard to find. If it takes you more than 3 seconds to find where a control statement begins, increase the size of your tab stop.

      Personally, I think that an editor should be able to be configured to always display code in one's preferred style, regardless of the format that gets saved to disk.

  84. Typing != copying by Kumiorava · · Score: 1

    Remember it's not copying if you type it over and over again. That's the way I avoid my code copy issues, works like a charm!

  85. I experienced the worst coding standard ever...... by Anonymous Coward · · Score: 0

    The lead programmer required everything be indented with 2 spaces, making everything less readable and annoying. It is also incompatible with almost every single programmer's indentation in the entire world, which made it more annoying. In addition, we had programmers on the project who refused to comply and so the lead programmer spent time reformatting their indentation, to which other programmers would get angry and reformat his. It became a very large waste of time, and a source of contention and battle.

  86. Formatting doesn't matter -- code quality does by Anonymous Coward · · Score: 0

    I think one of the important things to matter is that formatting, eg. brace placement doesn't really matter. The book C++ Coding Standards (just google it) first, rather 0th, rule is "Don't sweat the small stuff".

    Any developer can read and write a format -- what *is* important is just be consistent within the file and do reasonable indentation, line lengths, etc.

    What does matter are coding practices, eg. when or when not to make functions public, using smart pointers as much as possible rather than raw pointers (a C++ thing), or when to use a pointer to implementation to hide details. These things have more substantial impact on code.

  87. My pet peeve: mixed case syntax and Java style by Anonymous Coward · · Score: 0

    Please, please, please, can someone explain to me why:
           

    int theTotalOfTheVariables = theFirstVariable + theSecondVariable + theThirdVariable;
        theTotalOfTheVariables = theTotalOfTheVariables / theNumberOfVariables
       

    is clearer and "oh-so-more-readable" than:
         

    int total = (var_a + var_b + var_c) / nvars;
       

    Don't laugh! I've seen a similar exemple on one of the numerous "coding guidelines" one can find on the web. I've also seen code like this:
           

    for (Iterator<MyVerySpecialDataStructure> myVerySpecialDataStructureIterator = myVerySpecialDataStructureSet.iterator(); myVerySpecialDataStructureIterator.hasNext(); ) {
        myVerySpecialDataStructureIterator.next().getSpecialProperty().getProperty().printOnOutput();
     

    }

    I am pushing it of course, but just a little! Recently I had to take a dive into such a code where 200-character lines were common...

    I still try to understand why "modern languages" seem to hate underscores and common abbreviations althogether...

    Oh yes! I get it now! It is to be more readable...

    YAAC

    1. Re:My pet peeve: mixed case syntax and Java style by RAMMS+EIN · · Score: 1

      How about these all-time favorites:

      public static final int SOME_CONSTANT = 1;
       
      CustomerDetailsService customerDetailsService = new CustomerDetailsService();
       
      public void setFoo(Foo foo) {
        this.foo = foo;
      }
       
      import java.util.Collections;
      Collections.sort(list, new Comparator<Person>() {
        public int compare(Person x, Person y) {
          if(x.getAge() > y.getAge()) return -1;
          else if(x.getAge() < y.getAge()) return 1;
          else return 0;
        }
      });

      --
      Please correct me if I got my facts wrong.
  88. Less clear rather than more clear by Mutatis+Mutandis · · Score: 1

    I don't agree at all that putting braces on their own lines makes code more clear. My feeling is that the "waste" of vertical space is harmful because it makes it more difficult to get a quick overview of a code block.

    I prefer my code to look fairly "dense" in the vertical direction, because I feel that this highlights the structure more clearly. Whitespace is important, but excessive whitespace makes code look scattered and gives you the feeling you have to chase it all over the screen. Most IDEs automatically highlight matching braces anyway.

    I agree on using braces even for single statements, where it is not strictly necessary. This is much less confusing and error-prone.

    I also increasingly find braces to be syntactically useful all by themselves, i.e. outside the context of control statements. Braces are useful to divide code in blocks that reflect its structure, and can help to delimit the lifetime of temporary variables.

    1. Re:Less clear rather than more clear by CaptCovert · · Score: 1

      Whitespace is important, but excessive whitespace makes code look scattered and gives you the feeling you have to chase it all over the screen. Most IDEs automatically highlight matching braces anyway.

      Most IDEs these days -do- highlight matching braces. On the other hand, there are times when I can't see both my beginning and ending brace on the same screen (this is most common in large class definitions, but I've seen it in loops too). Without the beginning brace to line up with the ending brace, there are occasions where I don't know just how deep I'm nested, causing me to chase the code around to figure it out.

  89. I like the python (and C) style guides PEP by thc4k · · Score: 1

    See these:

    http://www.python.org/dev/peps/pep-0007/ C Style Guide
    http://www.python.org/dev/peps/pep-0008/ Python Style Guide
    http://www.python.org/dev/peps/pep-0020/ " Readability counts."

    I think python is the one language where "good code==natural code". Can't hurt to read the thoughts behind this ...

  90. try/catch by Anonymous Coward · · Score: 0

    the worst coding practise has got to be the excessive use of error handling for things that shouldn't have errors. I hate try/catch in C# about as much as I hate On Error Resume Next in VB6. Yes, there was the old VB practise of wrapping error handling around a file size check to see if the file existed. If it triggered then the file didn't exist. The same thing has been found in .NET, try/catch an attempt to read from a dataset to determine if it is readable. If it throws an exception, it's not readable. What happened to checking beforehand? Sometimes that isn't even available! I've encountered code that has as many as five layers of try/catch where a few if/else lines could have eliminated the need for all of them. Now don't get me wrong here, it has it's use, but just go easy on the try/catch. Seriously.

    </rant>

  91. Trinary ftw by Anonymous Coward · · Score: 0

    (something_is_true) ? do_something() && do_one_more_thing() : do_something_else();

    ifs and braces are for girlie boy programmers!

    1. Re:Trinary ftw by Thiez · · Score: 1

      And your statement makes no sense. It assumes that do_something() and do_one_more_thing() both return values, and that these values can be interpreted as booleans, and that the language does not simply skip do_one_more_thing() when it encounters that do_something() is false...

    2. Re:Trinary ftw by Anonymous Coward · · Score: 0

      Umm... yes.. if you write code that does that, typically they return booleanable values, and you probably don't care if circuits become short. So GP isn't dumb apparently...

  92. beyond the trivial by tallvegdude · · Score: 0

    I once had a colleague who insisted on using the following style for blockless-if statements:
            if( condition )
                  statement

    I figure you should either replace the above with
            if( condition ) statement
    or make it into a block as below.
            if( condition ) {
                  statement
            }

    The colleague's approach (which she learned from her father, a university prof who probably never had to maintain somebody else's code) was just waiting for somebody to add a second statement (similarly indented) that really needed to be in a block to work correctly. Yep, it happened.

    But in general, any reasonably skilled programmer should be able to either find or write a pretty-printer that will transform code to the desired brace alignment.

    I believe its more important that your coding convention deal with issues like how are exceptions/errors handled (I really hate code that spends 90% of its time checking return codes), how much complexity is tolerable in a single function (having ported somebody else's functions that were several thousand lines long), how arguments are passed (Oracle's C functions for accessing blobs are a wonderful example of what not to do, something like 12 arguments to read a range of data), and unit testing.

  93. I discuss everything: by incripshin · · Score: 1

    First is the brace style, because this is most discussed. I use K&R style as everybody should. The whole notion of it being easier to read when braces get their own line is totally bogus. Any coder worth his salt will use consistent indentation, so all code will tend to look like this under *any* brace style:

    if cond
            stmt-seq
    else
            stmt-seq

    Any style is readable. Also, I hate scrolling up and down just so I can see the rest of my statements because the screen is filled with filler lines with nothing but braces. And what is the deal with this madness?

    if cond
            {
            stmt-seq
            }
    else
            {
            stmt-seq
            }

    Where is the motivation behind that? It is pushing me into crazy. I'm going to start licking my lips and doing pencil disappearing magic tricks (saw that yesterday). Also, the GNU brace style is just too complicated to enter. I use vi and sometimes notepad++ in Windows, and I can't for the life of me imagine how such a brace style could be done automatically. And even if GNU does it, Linux certainly doesn't. Personally, I am wary of any occurrences of the RMS and GNU acronyms.

    As for managing horizontal space, it can depend on the language, but mostly indents should be eight column tabs and the screen is limited to 80 columns. Torvalds has a couple nice quotes I saw somewhere, but basically you're in trouble if you feel restricted by this. More than three levels of indents should be simplified into multiple functions, and really long lines are complicated to digest. An exception is Lisp or SML, where everything is an expression, and there are many many levels of nested parenthesis. I wrote a parser in SML, and I had to break down and resort to two character indents. Desperate times call for desperate measures.

    Another problem is when people say that they have a widescreen monitor and they're going to use every bit of it with an 8pt font. So I have a 13" monitor: am I screwed? I'm sorry if I like my sentences and paragraphs spanning across multiple lines. The most effective way of coding anyway is to have four instances of vi on the screen at once (you use vi, right?). Sometimes I'll have the editor split so that I can be looking at two parts of the code at once. Most of the time, you're working on multiple files at once (like headers) or have man pages up anyway.

    It doesn't seem like this has been discussed, but I also use the time-honored variable naming scheme of underscore-separated lowercase words. Camel case is just too hard to read, and it's inconsistent. Is it portTCP or portTcp? What the hell is Tcp? port_tcp is crazy easy. noXCoord or no_x_coord? (That's a point on one or two letter words.) For objects names, I do as Bjarne Stroustrup does in The C++ Programming Language: Capitalize the first letter, but do the same underscore style: Coca_cola_classic. That style I use mostly because whatever Stroustrup says or does in terms of C++ should be taken as gospel. An exception is anything you deem worthy of being a basic abstract type, like complex or hash.

    comments shouldn't show up after anything but indentation on a line. The only exception is that it can be a short note about a variable. For example, you might want to write something like this:

    struct range {
            size_t start;
            size_t end; /* noninclusive */
    };

    Otherwise you have a whole line for a comment, and maybe a line before that to separate it from the previous declaration.

  94. Hungarian Notation by dcollins · · Score: 1

    The buggest one-day productivity increase I ever experienced in my own coding work was the day I finally stopped trying to use Hungarian Notation. Even now I'm amazed at how much it slowing me down. I got maybe 3 times the work done after the day I ditched that.

    --
    We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
  95. Mod parent up!! by Capt.+Skinny · · Score: 1

    Hell, at first I thought (maybe hoped) the GP was being sarcastic.

    Throwing more hardware at something just so you can write poetic code is foolishness. It's often lazyness, but I think in the GP's case it's stubborn idealism.

    Code is written for the computer, and should accommodate the computer; comments are written for humans, so keep your poetry and prose there. Explain what you are doing in English (or Swedish, French, German, Swahili, etc.), not by making the computer jump through hoops each time a program is executed.

    Speaking of stubborn idealism, if you ever want to start a usenet flamewar, post to one of the database groups questioning whether something belongs in program code or a stored procedure. The deontological nutjobs come out of the woodwork, advocating their absolutisms that completely ignore efficiency and the possibility case-specific solutions.

    1. Re:Mod parent up!! by Splab · · Score: 1

      God I love the responses to my post.

      Sure shows quite a lot of people with zero clue hang out around here, just because code is readable doesn't mean its slow. But my grand parent wanted to drop readability and upkeep for the pitifully low clock cycle counts you save by having the parser stop parsing.

      Might wanna go look at a few loops, regex and see if you perhaps are doing that wrong before you go save on an echo statement. But hell what do I know.

    2. Re:Mod parent up!! by Capt.+Skinny · · Score: 1

      Like my mother always said, "Save your pennies. They add up quickly."

      But I guess that philosophy could also be regarded as stubbornly idealistic, so touche.

    3. Re:Mod parent up!! by Splab · · Score: 1

      True, but look at it this way.

      I can spend 10 hours a day going around the town picking up pennies people dropped, or I can spend 10 hours working at a burger joint flipping burgers. At the end of the day which 10 hours would give me more money? (Ok it might get pretty close with flipping burgers)

      My point is, don't waste time on something that by algorithmic standards have zero impact, echo overhead is just a constant. The real juice is in your loops, you might save a few "pennies" by spending hours shining up those echo statements, or you could save a couple of hundred bucks by moving a couple of loops around, perhaps add a missing index to your database - add a cache or something similar.

      While having those "pennies" might seem nice, you miss out on the real "cash".

      Ok that just about spend all the dough that metaphor had.

  96. 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.
  97. CASE statements for Delphi, SWITCH-CASE for C++ by Anonymous Coward · · Score: 0

    "So tell me genius, how else would you implement such a function without copying? if (a==1)
    {
    x+=b;
    }

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

    if (a==3)
    {
    x+=b;
    x+=b;
    x+=b;
    }"
    - by 4D6963 (933028) on Sunday July 20, @10:17AM (#24261957) Homepage

    Well, ok (even though I am not this "genius" person you are quoting!)

    Case statements, anyone?

    Specifically, switch & case, for C++ folks:

    (An example that fits YOUR code example, & how it would benefit by this (for readability AND performance), per this page ->)

    The Switch statement in C++:

    http://www.awitness.org/delphi_pascal_tutorial/c++_delphi/switch.html

    It'd be a big help for readability in your example(s), since you have a lot of a==1, a==2, a==3 stuff going on there (to aid in processing speed via break statements)... stopping excessive + unneeded evaluations from occuring!

    (For NOT executing comparisons that do NOT need evaluation (by using the break statement to pass them by once a solution/situation that satisifies has already been found, saving processing time))...

    Delphi (my fav) has CASE statements for this...

    APK

    1. Re:CASE statements for Delphi, SWITCH-CASE for C++ by 4D6963 · · Score: 1

      lol.. I.. I'm a bit confused.. you're not really being sarcastic, are you?

      --
      You just got troll'd!
    2. Re:CASE statements for Delphi, SWITCH-CASE for C++ by Anonymous Coward · · Score: 0

      No, no sarcasm intended.

      I posted that, just for improving the readability of his if-then statements, AND, to aid in not having to evaluate all the other possibles (which is what the switch-case-break construct does do, aiding efficiency of the if-then evaluations HIS code above would have went thru, ALL the possibles, even after having found a single answer)

      I.E.? A "double-bonus", specifically in his 'case' (pun intended) & code example using TONS of "if-then" evaluations... switch-case-break does so, for both readability AND efficiency.

      APK

    3. Re:CASE statements for Delphi, SWITCH-CASE for C++ by 4D6963 · · Score: 1

      Wow... where to start.. do you realise that if you really were to implement that function using my approach the resulting fucking would weight exabytes, right? lol so, improving the efficiency isn't required here. hehe. It was all a joke you know ;-)

      --
      You just got troll'd!
    4. Re:CASE statements for Delphi, SWITCH-CASE for C++ by Anonymous Coward · · Score: 0

      " do you realise that if you really were to implement that function using my approach the resulting fucking would weight exabytes, right?" - by 4D6963 (933028) on Sunday July 20, @03:00PM (#24264677) Homepage - by 4D6963 (933028) on Sunday July 20, @03:00PM (#24264677) Homepage

      Yes - I knew that...

      Now, I didn't read all the other possible solutions either, beforehand.

      (Some are quite nice - good logic, considering you are doing the SAME thing as long as the x evaluates (has value of) > zero... i.e.-> A positive valued integer apparently: AND STILL, a switch-case-break would work, anyhow! Is it "better"? No idea, by way of comparison to some of the other solutions offered here, a couple were pretty smart/elegant too).

      I.E.-> I came in, & just skimmed thru the content... & when I saw all those "if-then's"> I was like:

      "OK, this fellow needs help"

      Is all... & I didn't realize you guys were being 'wiseguys' about this here is all! What I didn't know, was that I didn't realize you guys were about making a joke of this, is all.

      -----

      "lol so, improving the efficiency isn't required here. hehe. It was all a joke you know ;-)" - by 4D6963 (933028) on Sunday July 20, @03:00PM (#24264677) Homepage - by 4D6963 (933028) on Sunday July 20, @03:00PM (#24264677) Homepage

      (Just trying to be helpful - though my help may be a "moot point", by way of comparison to others' solutions here, it might be of some use to somebody else reading is all, as another way of doing this, vs. the other solutions shown)

      APK

      P.S.=> Is there a "better way" of doing it? Sure, usually always is... but, I was just pointing out the uses & benefits of using case statements (specifically switch-case-break, per the if-then you had put up is all - to save having to eval ALL of the possibles, instead of leaving when an answer is found!)... apk

    5. Re:CASE statements for Delphi, SWITCH-CASE for C++ by colmore · · Score: 1

      I think managers should all read the above posts and think very very hard about their jobs.

      This is real.

      --
      In Capitalist America, bank robs you!
    6. Re:CASE statements for Delphi, SWITCH-CASE for C++ by Anonymous Coward · · Score: 0

      I think managers should all read the above posts and think very very hard about their jobs" - by colmore (56499) on Sunday July 20, @03:56PM (#24265145)

      I don't know where you're heading with that, but... a LOT of managers I've had in dept.'s @ various companies I had worked for, couldn't code @ all: I've never agreed w/ that, but... it's how it is!

      "This is real" - by colmore (56499) on Sunday July 20, @03:56PM (#24265145)

      Well, this CERTAINLY Is (has been in my experience, more often than NOT):

      I.E. -> Something's VERY WRONG if a dept. head hasn't done the job of his subordinates, @ least SOME of them, hands on!

      (AND, if you're going to head a coding team? Be able to @ least somewhat do the job)

      ---

      I don't know about you guys (speaking to folks that code on the job in some capacity here): I don't see much of that, @ least in my experience!

      Hey - & I'm not necessarily asking for the "best coder in the world" to be my boss in MIS/IS/IT dept.'s, but @ least a competent one to some degree (vs. someone who has NEVER done the job themselves, hands-on, professionally for years to decades @ least)

      AND - maybe not so much to contribute "excellent code" (purely relative term), BUT, to be a potential extra pair of hands to get work done IF need be (deadlines)!

      I.E.-> To help "get in the mud with the troops, & don't ask them to do anything you cannot do, yourself"...

      That @ the very least imo? Helps get respect from subordinates (even IF said mgt. figure is not 'excellent' @ it - which face it, varies, sometimes project by project even, or day by day, on various topics - nobody's 110%, all the time, on "all things magical & mystical" lol) & also helps make time to deadline estimations, too (crucial for mgt. folks, in deliveries schedules).

      ---

      HOWEVER/AGAIN - I see & have seen, CIO's for example, that have never coded @ all, or even built a machine themselves, in other words... leading others who do.

      Imo? An MBA does not qualify you alone, hands-on experience does, far moreso... & I don't see much of it myself in my MIS/IS/IT dept. leaders, over 15++ years now of coding professionally, coming from my "superiors"!

      (Oh, don't get me wrong - There WERE some bosses who did (knew all about this field, or large portions in a broad basis @ least), far & FEW between, & were some that were EXCELLENT - the best ones I ever had in fact knew a heck of a lot more than I did, but they were RARE... most though? MBA only stuff, etc.)

      APK

      P.S.=> AND Yes - I have been a manager in my time (& led a large chain of units in fact, month in & month out, on my evaluations + loss prevention stats, FAR before being a coder (decade & 1/2 ago almost), professionally))...

      Yes, there are OTHER b.s. tasks mgt. has to deal with (money, paperwork, risk taking, & people in short)... but, it matters to be able to be that "extra pair of hands/mind" @ times even if only then, & to get your employees respect (can't lead them effectively imo, w/ out that & experience hands-on in any field, especially having "risen from the ranks internally" gained experience, makes YOU, the more effective mgt. figure on ALL fronts - especially in decision making!)... apk

  98. Modularization.. by spiffmastercow · · Score: 1

    Not in the code sense, but in the project sense.. I.E. I work on this, you work on that. We can ask each other for help, but this project is my baby and that one is yours.

    I'm sure this is anethema to most coders, and that at some point it's not scalable, but it keeps inept coworkers away from my code.

  99. Constant variable ? by djinnn · · Score: 1

    No wonder you're confused...

  100. Auto-Formatter by Darth+Android · · Score: 1

    I don't really care how others style their code. Eclipse (and several other IDEs i've tried) has a wonderful tool - a formatter. Ctrl+Shift+F, and the code is rearranged to my own coding style (which, by the way, is { on conditional line and } on it's own line).

    --
    Do not meddle in the affairs of dragons for you are cruchy and good with ketchup.
  101. Write C using macros to emulate Pascal by Anonymous Coward · · Score: 0

    It has been used for serious programming. I'd venture most Slashdotters have come into contact with a program that was written like that. I'm not kidding - how fucked up is that?

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

  103. Star wars by Anonymous Coward · · Score: 0

    But it makes the else look like an imperial fighter!

  104. My 2 cents by Dar7yl · · Score: 1

    1) ! (K&R braces) // 'nuff said
    2) when formatting expressions, put multiple spaces in parens () - depending on nesting level
    ie. if ( ( exp1 || (exp2 & something) ) && (something-else) )
    3) about variable names - no hungarian notation, please. If the type of the variable is not apparent from context, I can da*m well look up the definition, thank you.
    A roommate of mine was working on a big project for a major telecommunications company, in a variation of Pascal. Their standard was to encode everything into the variable name - scope, persistance, type, and finally some sort of actual name. The names tended to be over 80 chars in length - making it impossible to simply scan the code. I heard they spent a lot of time in code reviews. I'm suprised they actually got the system to work.

  105. Hand Coding??? by Anonymous Coward · · Score: 0

    If it is C code for embedded systems we are talking about, there should be no hand coding or hand integration of code allowed. Most companies are developing their embedded systems with Model Based Development using the MathWorks tools. RTW embedded coder will generate 99.9% error free code from the models. Using UniPhi and QuantiPhi from SimuQuest (simuquest.com) in concert with the MathWorks platform allows all drivers to be integrated in the modeling environment, in the correct time threads. RTW embedded coder will then generate the entire software for the ECU in one go.
    Many companies today still make the mistake of trying to re-use old code. This is called infectious repetitis. This may seem attractive and logical at first glance, but does not take into account the massive effort to debug the hand integration and test on real hardware. Integrating and testing everything in the model gives you enormous confidence that the generated code will be correct. Confirmation testing is done on the hardware. If there are problems, either it is a hardware issue, or you need to look at your logic (in the model) or the accuracy of the plant model you did your algorithm development with.

  106. App coding standards that don't apply for OS by Anonymous Coward · · Score: 0

    I know that goto is "considered harmful", but when you are doing systems work, say an operating system kernel or piece of userland code solving a very systems-y problem, you are most likely working in C, a language that has no inherent support for exceptions (setjmp/longjmp doesn't count), and makes you reclaim unused memory by hand. So, for any sufficiently interesting function, you must allocate some memory, make a fair amount of function calls, check their return values for failure, and if they fail, deallocate everything, not to mention deallocate those same structures if you're successful too. In some cases, if you don't use goto, you can easily end up with long blocks of redundant code freeing everything at any point that something can fail.

    So sometimes it's easier to do:

    void *foo = NULL, *bar = NULL;
    int return_value = 0;

    // some code here

    if (function_that_can_fail())
          goto error;

    // more code

    if (more_functions_that_can_fail())
          goto error;

    // more code

    end:
          if (foo)
                free(foo);
          if (bar)
                free(bar);
          return return_value;
    error:
          return_value = -1;
          goto end;

    The other big lie is that functions should be short. That may be true for application programmers, but anyone who's worked on a big systems project can tell you that it's often an unattainable goal.

    It bugs me that some people are so narrow-minded about "rules" they've heard against a particular practice that they're unwilling to see that the rules don't fit every scenario.

  107. There are no best or worst way by Gusfm · · Score: 1

    Well, in my opinion there are no best or worst way, what exist are the ways you like and the ways you don't like.
    For example, I like codes this way:

    if(expression){

    }else{

    }

    Anyway, thats my 2 cents.

  108. I have the answer... by beaviz · · Score: 1

    After more than 150 years of experience in software development, I have come to a very simple conclusion about coding standards.

    Very good coding standard that is readable and maintainable: My standard.
    Very bad, unreadable and unusable coding standard: Everything else.

  109. No deviations, but errors, certainly by HBI · · Score: 1
    --
    HBI's Law: Frequency of calling others Nazis is directly correlated with the likelihood of the accuser being Communist.
  110. My first job (C++) by benhattman · · Score: 1

    The coding standard specified that programs could not use heap memory. A small exception was made for initialization code like this:

    int size = readConfigFileForSize();
    globalCharArray = new char[size];

    Everything else was required to be coded on the stack. And STL was discouraged as well. This was moderately real-time software, but the no-heap rule was still rather draconian.

  111. Step Into My Office... by maz2331 · · Score: 1

    ...because you're fuckin' fired!

    That sort of coding attitude of "just throw more hardware at it" is the biggest cause of websites that can't scale to handle any real traffic loads. I've personally bumped site performance with just a few line tweaks and optimizing a few SQL queries.

    Ask the machine to do something stupid, and it will.

    Ever see someone write "SELECT SUM(ColA) FROM Scores WHERE QID = 3" on a high-volume site? Do you understand the impact just that naive query is going to have on the back-end server?

    Here's a clue - you're going to end up with queries taking 30 seconds on that nice 8-core box with a RAID-10 array because you are constantly re-totaling 250,000 records and asking to do so 100 times a second. Time-out city coming. How about database table locks?

    Any semi-decent programmer will know better, and actually use a decent algorithm.

    You simply do not compromise your performance for laziness. And just because it runs fast on an unloaded test-bed doesn't mean it will work in the real world.

    Try getting linked to by Yahoo some time and see what scalable means.

    Or try writing an image processing filter with real response time restraints so you can send appropriate pan/tilt commands to the source camera. You need real code for that, not crap. And no, more CPU speed won't get you out of that one either, and no, you can't write it in Java or C#.

    1. Re:Step Into My Office... by Splab · · Score: 1

      Uhm...

      Just out of curiosity why are you rambling about basic SQL in reply to a PHP bashing?

      And using Yahoo, Google or Wikipedia as examples of scalability just shows what you know. Scaling for searching and hundreds of reads per write is simple, scaling for real time high volume critical data is hard.

      Just like all the other responders you seem to have completely missed the point, and top it up with some random rambling that just sounds fancy, but sure still doesn't look like you know what you are doing.

    2. Re:Step Into My Office... by igb · · Score: 1
      My theory is that it's an age thing. If you're forty or more, when you were at University you could trivially produce scenarios to cut code for where the problem was larger than the computing resources you had available. And for really quite small test cases, quick sorts really were faster than bubble sorts. And if you leaked memory, your shiny new code really did fall over. I've written code on systems with 128 bytes of RAM...

      But if you're younger, the difference between O(n^2) and O(n log(n)) was just a curiosity. You've never written code on a system without not merely VM, but so much RAM that the VM aspect doesn't really matter. And you're used to edit-compile-go taking a few seconds, not a few days.

      Which is great, and modern software environments are infinitely more productive than those of twenty five years ago. But when your website scales from a thousand records to a million records, or your code has to churn a thousand buffers per second for a year without being restarted so leaking one byte per operation just isn't acceptable, or it's running a 16-way machine flat-out and there's no end in sight, then you can't rely on hardware scale to bale you out.

      And that's when having cut code on a pdp8 or an SC/MP or a Nascom comes into play...

      ian

    3. Re:Step Into My Office... by jsdcnet · · Score: 1

      Oh man, you took me right back to a horror job I had once. They launched a site (on a weekend) for a big client. It was suppose to provide some sort of contract job market. One of the links was for "full time jobs". It was taking 40 seconds to generate the page. They called me (on the weekend) to ask me to get the ops team to add another CPU to the database server. I said, "Yes, that's a great plan, it will definitely get your 40 second query down to 38 seconds. How are you finding out if the job is full time?" "Oh jobs are entered in by hand and we do a SELECT * FROM JOBS WHERE JOB_TYPE LIKE '%full%'." I started looking for a new job on Monday.

      --
      no longer working for cnet
    4. Re:Step Into My Office... by maz2331 · · Score: 1

      The reason is simple: I despise the "just throw more hardware at it" approach, and can't stand bad code. It's always cheaper and better to write it correctly the first time than to have to return months later and fix it.

      Sometimes you need more hardware, and sometimes you need to look at the approach and optimize the algorithm and the code itself.

      The SQL example is just an easy one to point to, as I've seen it many times, and great hardware won't save bad queries.

      There's nothing wrong with PHP - it's a great scripting lanugage that can be used to actually write a serious program. But just like any other tool, it can be easily misused to create inefficient crap that's suceptible to XSS attacks, injection attacks (SQL and mail being biggies), etc.

      Embedding PHP in HTML is okay if you know what you're doing.

      Again, I've just had to clean up naive code many times that brought real business operations to a grinding halt, and the fixes have usually been pretty simple and SHOULD have been incoporated into the code from the beginning.

      The Yahoo, Google, et al. scalability is one thing, and the second example of high volume critical data is another.

  112. Macros by marcosdumay · · Score: 1

    Yep, a good support for macros may be the best feature a language can have. It replaces all the OO features, with several advantages.

    But, also, a good support for macros may be the worst feature a language can have. It leads to an unmaintenable mess where each part of a software is written on a different (unique) language and only the compiler can put it all toguether.

    As aways, the outcome depends on your team.

  113. ISO 9001 by Anonymous Coward · · Score: 0

    I worked for a company that was ISO 9001 and made a lot of noise about being so very ISO. Their coding standards were C only with extremely old coding styles that hadn't been used since the 70s. I am not even sure if those coding formats would even compile. The funny thing was that not a single employee was coding in c with the possible exception of a single individual who was doing some kernel hacking. Everyone else (hundredss) were using the usual mixed bag of languages popular at the time completely unaware that the company even had these useless standards. Yet a few times per year an ISO auditor would come in and say everything was OK. So to stir up some trouble I pointed out, to the auditor, that we were not following the C standards. I was ignored.

  114. Only 2 rules by Xowl · · Score: 1

    The only rule I've ever seen that matters: if you modify a file, keep the file's style consistent. Either code to match the rest of the file or (if you are making enough of a change to justify it), reformat/refactor everything.

    Other than that, as a lead or manager I list "stop words" that should tell a programmer to show the code to someone else and explain why they did something unexpected (goto, operator->*, returns nested deep in the middle of a function, etc.) and pick whatever naming and indenting standard is common on the platform, but don't get worked up over it.

    And the #2 rule (after in-file consistency): no standards discussion in code reviews. If someone violates common standards, tell them separately. Otherwise reviews can turn into nit-picky "move this here and change that prefix" 3p33n waggles.

  115. Coding Standards got me terminated by ashitaka · · Score: 1

    Why?

    Because I suggested to the managers that having some would be a good idea.

    They had none. Zero. Zilch. Not a Sausage. All coding methods were left completely up to the individual developers whims and experience.

    This was a software house that develops custom solutions for the world's largest legal firms. They are now part of one of the largest electronic information management corporations.

    I was inheriting follow-on projects where half to three-quarters of the project time was spent figuring our how the previous developer did the task. I saw this as a problem and tactfully made suggestions that we may want to set some standards and start some regular developer group meetings to discuss those standards and ways of optimizing our development time.

    Unfortunately the managers were only concerned that we put as many billable hours in no matter what the quality of the output which in many cases was absolute crap. My insistence that this was the case with more than adequate proof was not what management wanted to hear so the squeaky wheel was let go.

    So the moral of the story: Coding standards are a good idea but if the house you're working for isn't ready to implement any, it's time to look for work elsewhere.

    --
    If you don't want to repeat the past, stop living in it.
  116. My C++ thoughts ... by Anonymous Coward · · Score: 0

    Done properly, classes can do a great job of abstracting & encapsulating; too many classes (or levels of abstraction) can be extremely confusing and difficult to maintain.

    C++ gives you just enough flexibility to create a masterpiece or to hang yourself. I recommend using polymorphism, templates, and inheritance sparingly. Many of these concepts work reasonably well for GUI-related stuff, but can often obfuscate more complex algorithms. The "use sparingly" concept applies to other concepts, as well -- "gotos", "unions", and so forth.

  117. 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
    1. Re:Coding standards are stupid, better to localize by Shados · · Score: 1

      Not all coding standards are aesthetic though. The vast majority has to do with public APIs, localization, exception checking, string handling, and such similar things. You can't easily automate that (you can however, easily automate the checking of it).

      There's also code review that becomes troublesome if everyone use a different standard on their own machine. And depending on the language, code formatters do a lousy job (SQL for example).

    2. Re:Coding standards are stupid, better to localize by SuperKendall · · Score: 1

      Not all coding standards are aesthetic though. The vast majority has to do with public APIs, localization, exception checking, string handling, and such similar things. You can't easily automate that (you can however, easily automate the checking of it).

      That is true, but generally those kinds of standards are pretty well dictated (or at least offer an already widely adopted standard so there should be no need to define one explicitly) by the language you use - I was indeed talking only of syntactic differences (and there you could probably boil it down to brace placement and indentation spacing!)

      There's also code review that becomes troublesome if everyone use a different standard on their own machine. And depending on the language, code formatters do a lousy job (SQL for example).

      I had thought of code reviews, and basically there everyone would have to review against a chosen formatting (I was thinking of either the canonical standard or the presenters, so that he could speak to the code better - the reviewers can cope with a different format for a bit). Or, better tools need to be at hand to be able to talk about this or that function and placement within rather than pure line numbers. I don't see how anyone can really do a good code review without a great reverse engineering tool, which sad to say not many have access to.

      I would maintain that no matter how you arrange it, SQL is going to be badly formatted. :-) ( :-( ? )

      --
      "There is more worth loving than we have strength to love." - Brian Jay Stanley
  118. its preference and we change them over time by bussdriver · · Score: 1

    ///*
    if(    something    ){//    comment
        doSomething();

    }else{
        do_Something_Else();
        if(otherthing){
           //comment
            do_Other_Thing();}
    }
    //*/

    All that matters is others can read your code; its all preference or religion.

  119. Ignore White Space.. concentrate on meaning. by refactored · · Score: 1
    My coding standard is... indent your code in some consistent manner....

    And then, like the compiler, ignore white space and concentrate in the semantics.

  120. Re: BEHOLD! by Anonymous Coward · · Score: 1, Funny

    /* gcc -W -Wall -ansi -pedantic basic.c -D_STFU_MINUS_W -O3 */
    /* gcc -E -D_NO_INCLUDES basic.c | indent */
     
    #ifndef _NO_INCLUDES
    #include <stdio.h> /* use -D_NO_INCLUDES if you're going to use -E */
    #endif
     
    /* C-BASIC */
    #define SUB(_x) int _x (
    #define DIM int
    #define DiM , int
    #define BEGINSUB ) {
    #define LINE(_x) ; /* silence unused label warning */ goto _##_x; _##_x
    #define LET
    #define GOTOLINE(_x) goto _##_x
    #define INC ++
    #define UNLESS(_x) if (!(_x))
    #define RETURN return
    #define ENDSUB ; }
     
    /* multiply two numbers */
    SUB(multiply)
      DIM a
      DiM b
    BEGINSUB
      DIM i0, i1, i2
      LINE(100): LET i0 = 0
      LINE(110): LET i2 = 0
      LINE(120): GOTOLINE(140)
      LINE(130): INC i0
      LINE(140): UNLESS (i0 < a) GOTOLINE(210)
      LINE(150): LET i1 = 0
      LINE(160): GOTOLINE(180)
      LINE(170): INC i1
      LINE(180): UNLESS (i1 < b) GOTOLINE(130)
      LINE(190): INC i2
      LINE(200): GOTOLINE(170)
      LINE(210): RETURN i2
    ENDSUB
     
    int
    main (int argc, char *argv[])
    {
      int result = multiply (30011, 50021);
      printf ("Result = %d\n", result); /* note: 30,011 * 50,021 = 1,501,180,231 */
      return 0;
    #if _STFU_MINUS_W
      argc = argc; argv = argv; /* use -D_STFU_MINUS_W to get rid of warnings */
    #endif
    }

  121. Best and Worst Coding Standards? by Anonymous Coward · · Score: 0

    Rule 37 - No swearing in code comment sections.

  122. unbelievable by Anonymous Coward · · Score: 0

    it's about coding standards and all you can brag
    about is how you brace your code blocks.

    here's a coding practice you'll get more from than any bracing style:

    "cat sourcecodefilehere | grep '//'"

    that should give a precise description of what is going on.

  123. The best rule by professorfalcon · · Score: 1
  124. 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.

  125. Such generalisations are just rules of thumb by Anonymous+Brave+Guy · · Score: 1

    The Linus says:

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

    <sarcasm>Oh well, if Linus says it, it must be true.</sarcasm>

    I really hate this sort of dogmatic bullshit. Some algorithms are complicated, and don't factorise conveniently into self-contained chunks. It seems like every time we talk about function lengths or nesting depths or some similar issue, someone trots out the tired old lines about fitting on a screen, indenting to a certain level, or some such.

    Now, let me be clear: most of the time, these aren't bad ideas as rules of thumb. I absolutely agree that you should pull code into a separate function if it's meaningful and self-contained enough that the purpose of the function is clear.

    But if your code doesn't fit that description, for goodness' sake don't just yank out some part of it into a separate function because dogma told you to. That just spreads out an inherently complicated bit of logic so instead of at least being able to see it all in one place, you have to worry about jumping around into pointless functions that aren't self-contained or meaningful in their own right anyway, and is about the worst thing you can possibly do for readability and maintainability in difficult circumstances.

    If anyone thinks they know better, I'd be interested to see your efficient generalised subgraph matching algorithm, and so, I would imagine, would a lot of the academic and professional mathematical community.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  126. Automatic Formatting by DustinC19 · · Score: 1

    Every language has a grammar (of some sort) that determines how the code is to be broken down and ultimately executed. The problem is that there are multiple 'sentences' of grammars that produce exactly the same result when executed (e.g. the parse tree is exactly the same), because there are parts of the source code that have no effect on the execution (e.g. whitespace in many languages). Coding standards are really then about adding additional rules to the grammar to reduce the many exactly equivalent 'sentences' to one.

    The problem with these additional rules is that the often times there's nothing in the tool chain that enforces the standard. The ultimate result is that programmers bitch at each other for not following the standard, bitch about having to manually apply the standard, or the standard is simply ignored.

    What I want to know, is why does this all matter so much? Why isn't there tooling that will structure the source code to the way a particular programmer wants to see it rather than someone else's standard? It is structured data after all. Does anyone know of tools that do so? I personally haven't run across any (though I've also not spent tons of time looking, either...).

  127. Reasonable coding standards by Simonetta · · Score: 1

    I like your current firm's approach. I'm 'classed' as an electronics technician. Which means in nearly all jobs it's almost impossible for me go anywhere near code. But I still do a lot of coding; it just has to be invisible.

        I write a lot of small test fixtures with specialized embedded microcontrollers. For these tiny 'systems' to be efficient, they have to be small, cheap, very precise, and quick to program. I still do nearly all of my coding work in Assembler for controllers that cost less than $2. For example, a +5Volt/ground pulse that is exactly 40 seconds long (+/- 5 milliseconds) with a measurement of the time that it takes the voltage across an attached capacitor to fall to exactly +2.2V.

        The senior engineer devised this test 25 years ago for final calibration on a piece of medical equipment. According to the old procedure, it takes about ten minutes to set up the equipment and run through the procedure enough times to get an accurate result. But with my Atmel AVR Tiny13 85-cent microcontroller, I get an accurate result within a minute. I've been using this particular design for about a year, but still haven't got the approval to make it an 'offical ISO-approved change in the test procedure'. So I have to do it in secret, and could get fired if management found out that I was using equipment and procedures that didn't exist when Saturday Night Fever was still in the theaters.

        I code with lots of comments and paragraphs of text in comment blocks that explain what the code is doing. As much as possible, I want to be able to cut and paste code routines between programs in order to make the development process fast and easy.

        I remove all 'magic numbers' from the code. But I don't use THIRTY_SEVEN as a constant for 37. I would use a very brief explanation instead, like FIVE_MILLISECOND_DELAY_VALUE = 37. Personally, I dislike Hungarian notation. It works only for Hungarian genius coders like Charles Simoni who have come to learn about computer programming after mastering a half-dozen languages previously, like Charles Simoni. A word is an actual icon by itself, seperated from the other word-icons by spaces. Putting random characters in front of the word that is the variable name destroys the ability to instantly look at the word-icon and know what it means. If the Hungarian notation prefix is so important, it should be in a different color of text from the actual variable name.

        I wish that I had the luxury of hating the C language. I think that it is ugly, and difficult to understand. But it is slowly becoming the standard for microcontroller programming because there are so many individual types of microcontrollers in use. Each with its own assembler instruction set. So all of us 'secret-coder' electronic technician 'potentiometer tweakers' are having to become proficient in it.

  128. Everyone has their quirks by vaz01 · · Score: 1

    Some things I tend to do that that I'm not quite convinced are good ideas, but I do them anyway:

    // When things take multiple lines I try to line them up...  space before '{' here
    class SpaceDog extends RegularDog
                   implements AdaptedForSpace {
      // variable declarations lined up
      private String             name;
      private CanineSpaceMission mission;

      // a method like this... no space before brace when after a paren
      boolean bark(){
        // control structures written the same as function calls (no space after if);
        // one-lining simple conditionals
        if(inThePresenceOfAtmosphere) return true;

        if(Space.noOneCanHearYouBark()){
          // and a try block like this...
          try {
            frivolouslyAlterPhysicalLaws();
          }
          catch(NewtonianOutrageException e){
            beSadButDoItQuietly();
            return false;
          }
          // empty blocks without line break
          catch(PtolemianOutrageException ignored){}
        }
        produceIllogicalArf();
        return true;
      }

      // annoyingly verbose java getters and setters on one line if they're trivial
      public SpaceMission getMission(){ return mission; }

      public void destroyEnemy(EarthCat earthCat){
        // I do this sometimes, it lines up and the inside of the if block still indents once from the condition,
        // instead of indenting the second line further ahead and having the block un-indent
        if(EarthCat.inherentlyEvil()
        && earthCat.threatensCanineMission())
          destroy(earthCat);
      }
    }

    I'm not so sure about a lot of these habits... what do you think?  Do you have any style habits you're not so sure of?

  129. Anonymous Coward by Anonymous Coward · · Score: 0

    The best coding standard is to run a formatting script as you check in to source control. Then no one has to pay attention to it, just run their favourite format command as they open any code file.

    Really you're micromanaging your code. If your programmers need a standard in order to read the code, you're already in trouble.

  130. Coding styles and art form. by Anonymous Coward · · Score: 0

    Lets all just agree to disagree. Coding styles are very personal. I think of coding as an art form. You would never force an artist to paint a specific way. I suppose a coding style could be looked at as paint by numbers for the less gifted coders out there.

  131. Astyle by ponraul · · Score: 1

    Just agree on the astyle flags and don't give it a second thought. You can even get somewhat fancy and add astyle as a check-in hook in your revision control system.

    Other than that, don't waste time thinking up clever "best practices" and "standards" that will be forgotten in three days or waste time talking to boring, self-important pedants on slashdot.

  132. Standards tend to be used for the wrong things by Anonymous+Brave+Guy · · Score: 1

    Some things are very useful in coding standards, IMHO. The problem is that mandating the finer points of brace placement and whitespace usage is not one of them.

    For example, we write very portable C++ code at work, which is routinely built on several versions of several compilers running on several operating systems, where some of the combinations are state of the art and others are several years out of date. There are some standard language features that simply do not work properly on certain combinations, or that did not work properly back when this particular project was started, and which we therefore decide not to use at all to avoid either introducing portability problems now or having to retrofit all the legacy code to match what we'd like to do. These things go into our coding standard.

    Anyone who wants to use a prohibited language feature can make a case for changing the standard, but will be expected to show that the feature now works correctly in all currently and reliably supported build environments. They will also be expected to show that using the feature where they want to won't undermine any more general conventions. A common example with new starters is that we refuse to use exceptions anywhere, ever, for one of our projects. It's not because exceptions wouldn't help: on the contrary, they would make things much cleaner and we'd jump at the chance to use them if we were starting over. But back when this project was started, using exceptions was unreliable on some platforms and had unacceptable performance penalties on others, and we aren't going to start retrofitting exception safety onto over a million lines of code now.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  133. wrong timing by belmolis · · Score: 1

    Surely the Master Programmer asks to see the company's coding standards before accepting the job. Otherwise, he might end up in a position where he would be unable to follow the Tao.

  134. lax but informed: c++ stdlib/boost by Anonymous Coward · · Score: 0

    you forgot about that. i liked the one in boost libs. usually as small as possible, but as strict as possible to accommodate interoperability.

  135. Consistency is key by dkf · · Score: 1

    I use these coding standards; they seem to work well in practice. Others are possible too, but I wouldn't get too hung up over minor differences; consistency is by far the most important aspect. It also helps if you've got documented pre- and post-conditions for all functions.

    --
    "Little does he know, but there is no 'I' in 'Idiot'!"
  136. I like to see as much code as possible at once by SpecialAgentXXX · · Score: 1

    I will never understand the concept of putting so many spaces between the "ifs", the braces, the "elses", etc. How can you read the code if it's so spaced out? I also get rid of a lot of local variables by using the results of a method as the input to another method, etc. It can reduce the lines of code to where you only have to decipher 1 line.

    if (condition) {
    _____do something;
    } else {
    _____do something else:
    }

    See, much nicer to read than scrolling up and down. Those who use so many white spaces "can't see the forest for the trees." More code on screen = better reading. (Ungh, couldn't indent w/o _____)

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

    1. Re:if(ok && ).... by Anonymous Coward · · Score: 0

      Yes, this technique deserves a place in a programmer's bag of tricks. It's not very elegant but it doesn't have any serious drawbacks, other than possibly forgetting to check for "ok" (or "success", which is the variable name I usually use).

  138. single-line control-flow structures are evil by egypt_jimbob · · Score: 1

    Why not just have:

    if ( flag )

            salute();

    And save an extra line?

    Single-line ifs can introduce logic errors when you have to add an extra statement or when using a poorly written macro.*

    if, else, for, and while should always be accompanied by braces to clearly define what they do.

    * consider the following:
    #define foo() if (flag) do_foo()
    if (condition)
        foo();
    else
        do_something_else();

    --
    I am a leaf on the wind. Watch how I soar.
  139. diff friendly by nategoose · · Score: 1

    I suggest making choices that are diff friendly. I recently switched to keeping { on the same line as if/while/do/... when I realized that in large projects that sometimes makes the difference between a diff that makes sense and a total mess. I prefer when \t can be used to indent and spaces are used to format. The main thing is to just be consistent and enforce what makes sense.

  140. My first rule of good programming by brendan.hill · · Score: 1

    The first and foremost rule of good programming I've taught to my staff is:

    **GET RID OF DUPLICATED CODE**

    Every piece of duplicated code is a carnal sin. Even if a single line of code is duplicated, this is an offense. Deduplicating code has the following benefits:

    * Usually results in less code to maintain
    * Code you've written before is easily accessible to code you write in future
    * Less errors - if you make an adjustment to the code but forget to adjust it in all the other locations, bugs can make their way into production ("I'm sure I fixed that bug!?!")
    * It naturally results in a more structured architecture, which is vital for enterprise systems (or almost everywhere, IMO)

    Recently we outsourced a project to a software house. When they returned the code, I found that huge, huge chunks of code had been duplicated, all over the place. After much profuse swearing, I rewrote the software myself, from scratch, making the program more functional, friendly, flexible and reliable - and in about a third as much code.

    I'm obsessed about this principle, and take it to an extreme, and it's treated me exceptionally well.

  141. wrong direction........ by Anonymous Coward · · Score: 0

    actually talents communicate by thinking model
    not by eye-reading
    u read something by brain
    not eyes
    sorry

    coding stds......actually not really needed
    becoz if 2 ppl think the same thing in the same way....they can write the same thing in the same way

  142. re: Coding Standards by Anonymous Coward · · Score: 0

    Here are some VB.Net and general coding standards that I made and try to stick with when feasible. I have been programming for 11 years and have been burned, time-and-again by these mistakes from myself and others. Some of which are obvious, but others may take some expericence in to fully grasp the implications of not doing them.

    Never use a ForEach if you need to change the element iterator value or original group dataset, it will crash.

    Never substitute enumerators with hard-coded literals or constants (unless you like Find & Replace).

    Never reference member variables (regardless of scope) that are controlled by Class Properties; instead call the Property itself so that it can perform any encapsulated instructions.

    Don't confuse the branch short-circuiting effect of an ElseIf, with two seperate If statements. Always check your flow control.

    All Functions must return a value in all execution branch paths.

    Unless you need to save time and code, implement class properties instead of public member variables.

    Reserve the use of early-branch termination for cases in which the looping construct is otherwise uncontrollable/undeterminable (or excesive use of nested If's).

    Always check the parameters to a function, method or property for validity before usage. Check for null references and valid data ranges. If they're not correct throw an exception to the caller with a descriptive enumerated-interface message that would be useful programmatically.

    Whenever possible limit the parameter-less constructor (or any function for that matter) to only generic initializations only; this allows for maximum re-use in overloaded versions. (Implement the specific assignments in overloaded versions.)

    Always initialize variables in the parameter-less Class Constructor; while declarative assignments might be equivalent, those values can be overridden later in the constructor unexpectedly by another developer.

    Never return a "failure flag" from failed critical-success functions; throwing an exception will force the caller to resolve the issue that might otherwise go unchecked, the application generated exception should provide an interface error enumeration to allow easier identification of the root cause programmatically.

    If you have many classes with only one data binding point for each, consider implementing a generic interface for data binding re-use; this helps separation of concerns by abstracting the specific function names.

    All input parameters should be Escaped Names [], this allows an easy and clear method of identification for a target source within a functions scope; this helps to elminate reference ambiguity (for purpopses other than escaping reserved keywords).

    Take advantage of generic instance keywords: Me/This, MyClass, MyBase. Instead of naming member scope varibles with m_; this helps to elminate reference ambiguity.

    All variables being used for function returns must begin with an underscore or other identifier to allow clear identification of its purpose within a functions scope (in contrast to non-returned data).

    Always use descriptive naming, but try to keep the length reasonably short.

    Use Hungarian notation only if you plan on reading code print-outs a lot, or for compilers without IntelliSense.

    Take advantage of compiler keywords that implement automatic resource disposal whenever possible, database recordsets and connections would be a good example case; note the class must implement the "Dispose" Interface.

    Whenever possible implement Enumerations, member scope Constants/ReadOnly variables; they will centralize your statically-typed definitions and increase readability. Never use literals, this includes error messages and design-time default control values.

    When importing namespaces, always leave at least one level remaining; this is to reduce the chance of reference ambiguity and increase readability.

    Do not store Property member variables at the top of the Class; instead they should be

  143. 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
  144. A language obsessed with newlines by MessedRocker · · Score: 1

    Let's make a language where you MUST use newlines in every circumstance imaginable, and if the compiler detects a lack of a newline where there ought to be one, a picture of an old lady sticking her tongue out at you appears.

    Like this:
    if
    {
    $message
    ==
    "Enjoy!"
    }
    then
    {
    print:
    "You too!"
    }
    else
    {
    while:
    {
    2
    >
    1
    }
    do:
    {
    print:
    "HEY YOU DIDN'T TELL ME TO ENJOY!"
    }
    }

  145. Just one plea... by Anonymous Coward · · Score: 0

    Please, PLEASE just use consistent casing/underling on function names!

    My current work has hundreds of classes with methods like:
    GetName()
    getAge()
    get_address() ...
    CalcTotals()
    calc_totals_for_user() ...

    Not only does it look hideous and unprofessional, it requires looking up the exact spelling every time you need to use one.

    If nowhere else, please at least keep the INTERFACES clean with good coding standards. Everything inside can be as ugly as hell if I don't need to maintain it. If I need to use your interface however, I damn well want it to be clean!

  146. extreme programming by koutbo6 · · Score: 1

    if(x>5){doSomething();}else{doSeomthingElse);/*real programmers dont need new line or any contigous spaces*/}

    this style makes your programs smaller and run faster!

    --
    You speak London? I speak London very best.
  147. Maintenance Programmers by Ritchie70 · · Score: 1

    My team does almost 100% maintenance programming. It's rare that we write a new program.

    The application has been developed, in C, over the last 20 years.

    Our coding standard is "try to figure out what the file you're in mostly looks like. Do that."

    --
    The preferred solution is to not have a problem.
  148. One routine per source file - what a crock by synriga · · Score: 1

    At my shop there is a convention (for some projects) of one routine/function per source file with the source file named from the routine name. The reasoning is that you can find the source file easier given a function name. This coding standard was implemented over 25 years ago for FORTRAN and SIMSCRIPT projects. The principal engineer tries to enforce this coding standard on contemporary language projects, and can't understand why the convention is a really bad coding standard for C, C++, Java, or any other modern languages (not to mention impossible to follow for object oriented languages) . Some of us have some really goofy coding standards to deal with (or simply ignore).

  149. Re: Autocad, most ported program by Douglas+Goodall · · Score: 1

    When I worked at autodesk, the code had to compile on a huge number of target systems, so coding standards were about not breaking the code on systems with crippled compilers. It led to sad code,, but allowed autocad to compile on just about anything. Portability is very important, and standards help with that.

  150. Kinda like pr0n by marcus · · Score: 1

    Famous quote: "I might not be able to define it, but I can recognise it when I see it."

    Bad code is the same, especially when it is used as an example of good code. Just take a look at this.

    Let's hope this guy's employer doesn't pay him to code.

    --
    Good judgement comes from experience, and experience comes from bad judgement.
    - W. Wriston, former Citibank CEO
    1. Re:Kinda like pr0n by Bloater · · Score: 1

      Yuk

      That should have:

      #define MAX_LENGTH 8
      ...
      char binnumber[MAXLENGTH+1];
      ...
      int n = scanf("%8s%n", binnumber, &length); /* scanff - yuk */
      if (n != 1) /* do some error handling */
      // no strlen now

      and oh-god he's unrolled a loop and isn't checking for termination correctly... ARGH! Never unroll your loops! This is so bad there must be more stuff I haven't seen yet.

      This has to be an ironic example. Please say it is.

    2. Re:Kinda like pr0n by Bloater · · Score: 1

      Whoops, I got carried away with the number of bugs and didn't fix one that I meant to properly:

      #define TO_STR_INTERNAL(chars) ##chars
      #define TO_STR(chars) TO_STR_INTERNAL(chars)

      int n = scanf("%" TO_STR(MAX_LENGTH) "s%n", binnumber, &length); /* scanf - yuk */

    3. Re:Kinda like pr0n by Kitsune818 · · Score: 1

      I hope you mean never unroll your loops in a compiled language. In scripting, you often can't avoid it.

    4. Re:Kinda like pr0n by Darfeld · · Score: 1

      I hope you mean never unroll your loops in a compiled language. In scripting, you often can't avoid it.

      Why?

      --
      (\__/) This is Lapinator
      (='.'=) copy it in your sig
      (")_(") so it can take over the world
    5. Re:Kinda like pr0n by SQLGuru · · Score: 1

      Not sure about the "why" in scripting, but there are cases where for performace you might want to unroll a loop, but you have to know an awful lot about how and when the code is being used in order to justify unrolling it (since you are now locked to a specific number of iterations).

      The other time that it's good to "unroll" a loop (I guess technically it isn't unrolling them, but eliminating them) is when you are using cursors in the database. If you can rewrite the logic into a SQL statement (or two) instead of using a cursor to iterate, you can (usually) gain a lot of performance. [In fact, seeing cursors overused at the DB level is one of my biggest pet peeves....they have their place, but too many developers rely on what works in their app level language which isn't always best in the DB.] SQL is an SIMD language unlike most languages that programmers deal with, which are SISD; if you can learn to take advantage of that, you can go a long way in the DB world.

      Layne

    6. Re:Kinda like pr0n by Ihlosi · · Score: 1

      Not sure about the "why" in scripting,

      In a compiled language, the compiler should be able to unroll the loop for you, given the right compiler options, unless it is absolutely brain-dead. So, leave the unrolling up to the compiler - it can do that better than you and you're not messing up your code.

      The interpreter of a scripting language usually can't perform unrolling.

    7. Re:Kinda like pr0n by Darfeld · · Score: 1

      Why would I use a scripted language if performance is that important?

      --
      (\__/) This is Lapinator
      (='.'=) copy it in your sig
      (")_(") so it can take over the world
  151. I hear ya by p3d0 · · Score: 1

    I just undid a mess like that a couple of years ago (a mess I had introduced several years before that). It was very gratifying to see the dual-maintenance problems vanish.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  152. A strange one for Objective-C by GrahamCox · · Score: 1

    Recently I prepared some code I'd written in Objective-C for use by another developer. They were licensing the source and wanted me to use their coding guidelines where possible. One of these had me scratching my head.

    When objects are instantiated in Objective-C, the runtime implements the language specification that states that all data members are initialised to zero. In the light of that, the developer's insistence that every member variable be ASSERTed to check that it really was zero seems ridiculous. I mean, if you can't trust the runtime to do what it says it will do and what the spec insists that it does do, what can you trust it to do? By that logic the only safe way forward is to start by implementing your own runtime...

    The developers argued that ASSERTs are not *supposed* to execute, so it's not as if they are slowing things down... But I really think that seriously missed the point. One practical effect of adding all those ASSERTs at their insistence was that it made any initialisation code that set things to non-zero values much harder to pick out, read and check. Now that particular customer has moved on, I'm gradually removing all that pointless clutter as I re-encounter it...

    1. Re:A strange one for Objective-C by EkriirkE · · Score: 1

      In these cases, in C, I just to a memset

      --
      from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
      to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
    2. Re:A strange one for Objective-C by GrahamCox · · Score: 1

      You missed the point. The runtime *already* guarantees that it has done a memset (or calloc) so that everything is zero when you first allocate the object. Thus you can assume that's the case and so ASSERTing it is pointless. If you can't trust the runtime to actually do that, what can you trust it to do? (given that the runtime is a very important and non-optional piece of core code that implements the entire dynamic-dispatch system that everything you write in Obj-C relies on).

      The presence of the ASSERTs is not just pointless, it obscures the code that needs to assign any non-zero values, so makes the code less readable and harder to maintain.

    3. Re:A strange one for Objective-C by EkriirkE · · Score: 1

      No, I know what you're talking about, I was meaning in the cases when you are unsure if something is initialized or not.

      --
      from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
      to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
  153. Re:Multiple exit issues - "structured programming" by IBitOBear · · Score: 1

    Actually, "a single point of exit" is the whole of the law for being a "structured program" in the classical sense.

    From the practical sense, it makes debugging happier since you have one place to put a breakpoint.

    What most people call "refactoring" I usually call "code origami" because it is a useful moment to apply both science and art. 8-)

    Consider the average function returning bool. Fro the most part, if you can determine that a function is either "normally true" or "normally false" and then all of your structure analysis can be in terms of "varies from true" or "varies from false" (e.g. you start with "bool f() { bool retval = true; return retval;" as a normally true function and find the false cases as necessary.

    When you find that "normally true" and "normally false" logic is intermingled, you instantly know that the function should be split.

    When you add other rules like "a function either does or decides" (e.g. decision structure is different than computation etc) and so on, you get lots of natural divisions for your decompositions.

    Oddly, this is exactly orthogonal to the functional programming model where iterative collateral definitions of a function bodies with guards, reduces the code body to declaratives.

    So anyway, the prohibition doesn't come from misunderstanding of early program proving technology. It comes from the root theoretical work relating to state isolation and "demonstrable correctness". That turned into some of the early provability tools. But there is a difference.

    --
    Innocent people shouldn't be forced to pay for inferior software development.
    --"Code Complete" Microsoft Press
  154. Don't tailor to the least capable developer! by Lord+of+Kaos · · Score: 1

    No, really. You can overdo it this way, severely limiting senior developers capabilities. For example, a C++ project I worked on several years before had the following guidelines, which obiously were designed according to your focus: Multiple inheritance was banned (whoa, dangerous). Result: Couldn't combine object hierarchy and technical interfaces. Templates were banned on reason of "code bloat problem". Result: Superfluous copy-pastelike code (bloated anyway). So sticking to these guidelines made good design somewhat tricky. We ended up restructuring the rules, going for "rules" of code formatting and naming conventions and "guidelines" for preventing buggy code. Each rule and guideline was supplemented with reasons for this rule, examples, and a list of conditions permitting rule violation.

  155. Reference material by Anonymous Coward · · Score: 0

    http://en.wikipedia.org/wiki/Indent_style

    I think this is a must-read for anybody talking about coding styles, although the article's title is somewhat misleading.

    It also explains why K&R is actually not the coding style used by K&R in their code - it was the first C book editor's choice to reformat the code so it takes less space on paper, without any thought about readability or other criteria, and without consultign with K&R. Many monkeys reading the book and using the code style afterwards led to the spread of this awful style, not the guru's preference for it.

    Hungarian: I always used it, and found it useful. However, Hungarian may mean different things in different languages/environments, so you have to come up with your own conventions. Dumb conventions, in place just for the sake of it, aren't really useful.

    Line length: due to physiology of reading, no matter if on screen or off screen, lines should never be longer than 70 characters, and typically at most 40 characters. Reason behind it: when you read, you don't glide your focus along the lone, but instead focus successively on fragments on lines, the length of the fragment depending on your reading habits. When reading code, programmers instinctively tend to span a portion of a text line large enough to grok one line at a time, if it's not too long - it ensures that most of the times the portion of the line constitutes a semantically complete unit. If you make lines longer, the physiological inability to focus at once on too long a line will make you build up one semantical entity from more than one piece of text, which is more effort. If you break lines too often, you will be in the same situation, not because you couldn't focus on more characters at a time, but because you aren't used to focus on more than one line at a time.

    This is also the reason (actually, my reason) behind braces on separate lines. A brace says "begin/end block". An else, if or something else, is a different concept. If I mix them on one line, I confuse the later programmer which will be reading my code, whether you believe it or not.

    Reasoning such that too much white space allows for too little code on screen I don't buy. You have large monitors nowadays, and if you still don't have enough vertical space on your monitor then probably your code isn't well factored.

    Just to set things right, I'm not an anonymous coward, just lazy - creating an account means work.

  156. Re:braces @Dachannien (617929) by Anonymous Coward · · Score: 0

    Oh god, please don't share your ideas!

  157. Best practise by jandersen · · Score: 1

    Rules of thumb:

    1. Proper indentation
    2. Proper comments
    3. Proper blockstructure
    4. No code block exceeds a screen page (80 col x 25 lines)

    The first three should be obvious, I hope. No. 4 is about legibililty for everybody involved. It may well be that you feel comfortable with very long lines and use a small font, so you can hold 200 lines on screen, but the common minimum standard is still 80 x 25, and some people still prefer to use that format.

    The worst standards are the ones that have too many details - it's like micromanagement. Trust your coders to do the right thing, but enforce a few, important rules. The way source looks should only be a matter of importance if it helps make the code more understandable and thus easier to change or debug.

  158. You must have some serious prima-donna programmers by Xtifr · · Score: 1

    I have my own preferred formatting and naming styles, and I use them for my own code. When I work for a company, I use the company's preferred style, if they have one (though I'll happily fall back on my own). Anyone who can't cope with that simple logic probably doesn't deserve to be working at your (or any) company. Certainly anyone whose productivity is impaired when they're not working in their own preferred style is probably overpaid.

  159. Had some nice coding conventions in college. by Anonymous Coward · · Score: 0

    In a java class the teacher taught us some conventions that we were supposed to use for the class (although we were allowed to use other conventions if we really wanted).

    Instance fields were my_something
    Parameters were the_something
    static final things were WHATEVER_VARIABLE
    Class names were ClassName (and thus consistent with most other classes)
    method names were methodName (also consistant with most other public methods)

    Also, the variable names were supposed to be very descriptive (for full credit), such as, for example, my_brush_color (paint clone), or my_current_piece (tetris).

    I really liked these conventions, and still use them whenever I can. I feel it makes the code easy to maintain and read.

  160. Programming practices by em0te · · Score: 1

    If we're talknig about simple single if else statements great. But more often than not, one gets a convoluded nested if, which for readability purposes could be often beter used in case arrays One practice I came across was that if the algorithym had more than 3 nested if statments then we used a case array
    case(1,2,3,4,5,6)
    {
    :1(do something)
    :2(do something else)
    :3(do something else)
    :4(do something else)
    :5(do something else)
    :6(do something else)
    }

  161. 3000 line Method - YES METHOD by posinabox · · Score: 1

    Some coding standards are just common sense and its sad that there are a crap load of developers/programmers without much of it. E.g. I work for a major financial institution and have seen extremely bad habits such as a 3,000 line method. I mean in all honesty, just one look at the code (even with great IDE's that can navigate to closing curly braces) you get so worn out before even debugging. What's sad is that the culprits churning out such crap are Senior Developers. I think emphasis should be placed on modularizing your code. With modern IDE's this is not much to ask for.

  162. Totally subjective, hence hopeless... by SlideRuleGuy · · Score: 1

    Coding style is totally subjective, hence discussing it is almost pointless. So I offer just a few (meta-)observations from 20 years in the trenches:

    0. For senior developers, terse is still quite understandable, and hence "better". More stuff on the screen at one time = good.
    1. For beginners just learning a language's idioms, or developers who aren't that bright, cut/paste is more understandable, hence "better". It may take up more space, but each line is more easily comprehended in isolation. (I have seen developers with 10+ years of experience, still coding heavily with cut/paste.)
    2. If a team of headstrong people already use diverse styles, imposing a standard will create ill will.
    3. For a team of easy-going, mature developers, a modest coding standard is welcomed.
    4. Everyone will argue for the form they are most comfortable with, and that is totally subjective. Sure, we can cite nice sounding reasons for our preferences, but the opposition can do the same. (And is it always the case that the smartest carry the day?)
    5. Yes, there are styles that are "way out there", but those coders won't speak up. They will just keep coding in their style, hoping nobody notices.
    6. Until there is a way to measure the average cognitive effort required to understand a given style, relative to other styles, we may as well drop this debate and do something more useful with our time.

    It all adds up to lost profits for some, and job security for others. Ain't life grand?

  163. Can't see the forest for the trees by Giant+Electronic+Bra · · Score: 1

    This sort of ant-scale concern is just too trivial to waste time on. Instead of chasing around trying to make everyone put their braces where you want them, spend the time on good code reviews, good design, and other things which actually ARE important.

    Coding is MAYBE 10% of the total work involved in creating a piece of software, and by far the least critical 10% at that. Even in the category of coding practices such trivia as what you name local variables and how you indent blocks is at the very low end of the scale of importance.

    I started out coding in FORTH, and I really do believe that experience taught me a lot. Never make a function more than 5 lines long. If you have 40 lines of junk inside a block, it should be a function/method of its own. NAME things descriptively and design your APIs to expose WHAT people want to do and not HOW it is accomplished. Learn and understand patterns and refactoring.

    Forget about where the stupid brackets go. No one coder should be the only one working on a piece of code anyway, the whole team should be looking at it within 2 days of its birth. So if your process is right, then code style will just naturally converge to a consensus.

    --
    "Malo periculosam, libertatem quam quietam servitutem." -- Jefferson
  164. Info-ZIP Workgroup's "No Feelthy" Rules by Toad-san · · Score: 1

    Just to add a little ancient history in this area:

    Long long ago, there was an international Usenet workgroup that formed to create a universal PKZIP-compatible zip compressor / decompressor utility. We were getting tweaks and hacks from all over the place (for different systems and compilers, as well as actual functional improvements and bug corrections). And we were posting not only full source updates, but also the latest and greatest changes as diff files. (Remember them?)

    As a result, we couldn't have make a decent diff when someone had changed 3-space indents to 4, or tabified the code, or uppercased all the constant names. So we'd run all the received code through a utility / script that would set "standard" indents, cases, wraparounds, etc. THEN we'd do the diff against the old version.

    For a year or so I was the coordinator / moderator, posted the source (to good old SIMTEL.NET), distributed the diffs, etc. And I wrote up the "No Feelthy" rules (e.g., "No Feelthy Tabs") to give everyone a baseline.

    There's some history here:

    http://mit.edu/~mkgray/jik/sipbsrc/src/unzip-5.12/ZipPorts

    As you can see, they've updated it (and even gave me credit, hooray!) ... but still kept it pretty simple.

    Heh .. funny to re-read all that after all these years. (It has been a VERY long time.) Real Stone Age stuff, I know, but there were some serious limitations back then that people don't even know about today! (Yeah, and we had to walk through 4 feet of snow to school, uphill both ways!)

    Yep, those were the days, all right. [kaff][kaff]

    David Kirschbaum
    Former Info-ZIP Coordinator

  165. infinite loop by Anonymous Coward · · Score: 0

    Our company does not have coding standards. But every once in a while, we're told that something is "supposed to be standard for everything!" Then we have to go back and rewrite everything we did previously to match...

    It's very efficient. Like hamster wheels.

  166. Uncrustify before reading by natoochtoniket · · Score: 1

    The purpose of "coding standards", as opposed to "design standards" or "best practices", is to make the code easier to read and understand by making the formatting consistent. But, unique people with specialized education or experience are, well, unique. Each person has unique background, preferences, and habits.

    So the meaning of "easier to read and understand" is different for each person who has to read and understand the code. Forcing a programmer to write in a style other than his/her preferred style actually increases errors. And, forcing people to read thing written in styles that they don't like is likely to slow them down. So the right answer is to allow each person to read and write code in his/her preferred style, and to have a tool that puts code into that style on demand.

    We use "uncrustify (http://uncrustify.sourceforge.net/ ). Uncrustify is, basically, a feature-rich, flexible, and configurable "beautifier", that works on several C-like languages. It puts code into whatever style the user likes, based on a configuration file in the users home directory. By using uncrustify, each programmer can read in his/her preferred format, even if it is different from the authors preferred format. This minimizes format-induced errors, maximizes ease of reading and understanding.

    It also avoids silly arguments about code formatting, so we can spend our time arguing about more important things, like meaningful variable names.

  167. Coding Standards by Anonymous Coward · · Score: 0

    Hi,
    Long time reader.. first time poster but when I was reading the story and saw "or that code should be indented with tabs rather than spaces, or vice versa" and knew I had to post this story...

    My friend had to go through some code at work one day and called me over and said "take a look at this". As we tend to show off bad examples of code (and there is lots of examples to show) I knew it had to be awesome b/c it warranted a live example as opposed to a verbal / written story.

    The code looked something like this...
    if(something){ move this field to that field move another field add some fields } etc etc etc.

    We looked at the the comments up top, saw the developer and for some reason decided to change the resolution to match her resolution (800X600!! - who the fck uses 800X600?!). The code then lined up perfectly... she used spaces to go to the next line!!!!! Probably the best example of coding I have ever seen in my short 5 year career.

  168. Ultimate Goal by andrewjj20 · · Score: 1

    I have seen good and bad looking code from good coding standards. The best idea that I can come up with is: as you are writing the code realize that you are writing it for 2 things, 1. the computer and 2. the next guy that has to look at your code. if you do this then your code will be efficient and easy to understand; this is after all the goal of a coding standard

  169. I've got only one standard. by mweather · · Score: 1

    Tell the engineers everything gets coded in .Net, but you can't use Visual Studio. It's like watching a deer in the headlights.

  170. Re:Multiple exit issues - "structured programming" by Animats · · Score: 1

    Pascal was built for that specific model of structured programming, but it's not a correctness requirement. As long as all the exit points go to the same place, there's a "single point of exit", even though it's reachable by multiple routes. "break" and "return" all lead to one exit point, so there's no real problem.

    Exception handling, however, does bypass the return, and adds some interesting issues.

  171. Tabs or Spaces or Enter? by Anonymous Coward · · Score: 0

    I have been coming to this website for years and saw this article and decided to make my first post when I read the line "or that code should be indented with tabs rather than spaces, or vice versa".

    My friend at work was asked to look at some code one day and called me over to his desk to witness a masterpiece (we normally show off bad examples of code to each other for laughs). Right away I knew it was going to be a good one as it warranted a visit and was not communicated via email or office communicator.

    I looked at the screen and it appeared something like this:

    IF( something equals something ) {________ then
    move variable a to variable b;______ do something else;________ }

    **Personal note: The underlines are spaces.. I got owned by the filter

    I was amazed... we tried to figure out what the f was going on. We looked at the comments to figure out who wrote the code and then decided to change his resolution to her resolution (which was 800X600 - who the f uses 800X600?). After the change in resolution, the code lined up perfectly. So she used spaces to proceed to the next line of the editor.

    She still works here..

    1. Re:Tabs or Spaces or Enter? by synriga · · Score: 1

      This is spooky. It sounds like we work for the same company with the same uninitiated programmers.

  172. Copyright in first 512 bytes by DalDei · · Score: 1

    When I worked for we were working on an *nix project. This was fairly new for the company which typicaly produced Mainframe products. One of the Company Software Requirements was that a copyright notice had to be within the first 512 bytes of every program and object module.
    I'm not talking about the source code, I'm talking about the exe's (a.out's ) and objects (.o's) and shared libraries (.so's).
    Supposedly this was some kind of legal requirement for all software everywhere ... but I'd never heard of it before or since ... I think it was some Lawyer's interpretation of some 1950's law ...

    Naturally, Big Company's Mainframe Software had a compile flag to do this ... so it was no big deal. But we were using C and there was no such concept of forcing an arbitrary string into the first 512 bytes. So ... some "creative" individual found a way ... by declaring a global static function like

    static void aaaaaaa_Copyright_1980_International_BigCompany_BlahhBlahh() { }

    we were able to comply with this coding standard ... the linker's would sort the function names in the a.out headers and this one function name would happen to (usually) be in the first 512 bytes of all output files. So we had to include

    #include "BigCompany_Copyright.h"
    in every .c file just to make sure ...

    And then ... we had to do some tricks to make sure the function wasnt optimized out in the final link pass ...

  173. Are you sure? by cocoa+moe · · Score: 1

    To reiterate: matching braces should line up horizontally AND vertically.

    That doesn't make sense. If it is the same column and the same line as the opening brace you either have more than one closing brace or it is in the exact same position as the opening brace. This is difficult, even in editors that support overstrike characters and results in nothing being beween the braces.

    On the other hand: code that isn't there can't possibly include any errors.

    1. Re:Are you sure? by gfxguy · · Score: 1

      Yes, you're right. Smack me one.

      It should be that they line up horizontally so that they'll line up with a vertical line.

      --
      Stupid sexy Flanders.
  174. It depends on the language by cocoa+moe · · Score: 1

    The consensus of the posts I read here seems to be that coding standards regulate code layout and are not very useful. My experience is different.

    I was part of a small team that wrote the coding standards for C++ for a medium sized part of a really large company. We designed the standard to be usable throughout the whole company though. We took three years to complete a set of about 150 rules. None of them is concerned with code layout or a mere matter of taste.

    But I suppose it is a C++ thing. No other language contains such a vast array of error prone constructs. Many of the rules in the coding standard are merely help to keep you out of trouble. We mandate not to use C-style typcasts for example, we require you to use assert() and we ask to use "-Wall" and other means to make errors detectable at compile time.

    I think languages like oberon, pascal, java and other better designed languages would reduce our set of rules to about 3 or 4 basic suggestions like:

    Let names of variables indicate the meaning of the object rather than its type.

  175. Girls, girls.... by xianvox · · Score: 1

    Your coding styles are both pretty.

  176. My style, as if it matters by EkriirkE · · Score: 1

    I don't use curly braces unless I'm performing multiple lines of code for a condition or loop

    bool myfunction(int a,float b,char *c) {
      if (true) something;
      else something;

      if (true) something;
      else {
        multisomething;
      }

      if (true) {
        multisomething;
      } else something;

      if (true) {
        multisomething;
      } else {
        multisomething;
      }

      a+=5; //None of this a=a+5 stuff
      a<<=1; //I shift integers when multiplying/dividing in powers of 2 (in this case a/=2 or a=a/2)
      b++; //I use ++ and -- when simply incrementng/decrementing.  None of this b+=1 or b=b+1 stuff

    //I like my goto loops only when there is no condition immediately testable at the top or bottom.  a "while (1) {}" would suffice, but feels wasteful (an always true condition test)
    //I reverse indent my labels, and indent the code further than the previous-to indent
    loopTop:
        stuff;
        stuff;
        if (condition) {
      badCondition:
          stuff;
          stuff;
          goto loopTop;  //a "continue" would replace this in a "while (1)"
        }
        stuff;
        stuff;
        stuff;
        if (condition) goto badCondition;  //jump to my condition code, as its a waste to repeat same functionality, or the overhead of passing variables and pointers to a subroutine
        stuff;
        stuff;
        stuff;
        if (condition) goto badCondition;
        stuff;
        stuff;
        goto loopTop;
    loopEnd:
      return true;
    }

    --
    from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
    to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
  177. prettyprint by gatkinso · · Score: 1

    Use whatever style you want. It is getting pp'ed before commit, however.

    Other than that, the rules are minimal: no Hungrarian notation. No all capital identifiers.

    Carry on.

    --
    I am very small, utmostly microscopic.
  178. Good and bad by spaceyhackerlady · · Score: 1

    One of the best things for a programmer: learn to type. Among other things, it becomes natural to use longer variable names that might actually be half-assed descriptive. A current project has procedures with names like SetDefaultConfiguration(). Three guesses what that does. :-)

    One bizarre coding standard from an earlier project set a maximum length on variable names, Since they had mandatory prefixes to say what component they came from, this did not enhance readability.

    This stuff is here to serve us, not to bind us. If coding standards become too onerous, the advantages in development and maintenance effort are lost.

    I still think Hungarian Notation is a crock.

    ...laura

  179. FORTRAN-based coding standards by fishexe · · Score: 1

    Just remember:
    Real programmers can write FORTRAN in any language!

    --
    "I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
  180. Some thoughts by GWBasic · · Score: 1

    Some thoughts:

    Try to follow the established style(s) of the language until you're an expert.

    Don't fight frameworks or spend a lot of time hacking around their deficiencies. If you have to work very hard to do something simple; you're doing something wrong.

    Code generators should be highly limited in scope; they should only touch a single layer of your application at a time. This is because code generators tend to be quickly written and make lots of assumptions; code generators that dominate many layers of scope will be a nightmare when assumptions fail.

    Don't write lots of class hierarchies that are highly similar. The code needed to martial data between types is error-prone and labor-intense.

    Nothing comes for free.

  181. Measuring the effectiveness of coding standards by amead · · Score: 1

    Coding standards are a good idea, but how do you measure the effectiveness of using the standards? Does anybody know of any studies on the subject?

  182. Linux kernel coding style by DVega · · Score: 1
    Taken from Linux kernel coding style

    First off, I'd suggest printing out a copy of the GNU coding standards, and not read it. Burn them, it's a great symbolic gesture.

    --
    MOD THE CHILD UP!
  183. My personal Coding Standard by spaceman375 · · Score: 1
    is Humor. You know that someone, most likely not you, will have to read your code at some point. Others have spoken about formatting and readability; this standard improves working conditions. Put a joke or three in there. How long a variable name is in the source code doesn't affect the size or speed of the compiled binary. If you only need that variable once or twice, make it funny. Better yet, tell a short story or quote a movie.

    Some of my personal examples:

    When I opened the employee file for a payroll application, I used the filehandle "the.downtrodden.masses."

    One of my favorites was when I assigned a few variables ahead of time and was able to write (and use):

    open(the.pod.bay.doors, please.HAL) else print Im.sorry.Dave.I.cant.do.that

    Contributing to a happy workplace is essential to good code!

    --
    On the one hand you take life too seriously, and on the other, you do not take playful existence seriously enough. Seth
  184. Worst C++ coding style: Microsoft STL by Qwertie · · Score: 1

    The MS STL looks like a mess. All identifiers begin with an underscore, braces are indented, some structure such as try blocks are not indented, and names are not especially descriptive (_Xlen, _Umove, _Alval?). Here's typical code from vector<T,Allocator>...

            // TEMPLATE CLASS vector
    template<class _Ty,
        class _Ax>
        class vector
            : public _Vector_val<_Ty, _Ax>
        {    // varying size array of values
    public:
            ...
        void reserve(size_type _Count)
            {    // determine new minimum length of allocated storage
            if (max_size() < _Count)
                _Xlen();    // result too long
            else if (capacity() < _Count)
                {    // not enough room, reallocate
                pointer _Ptr = this->_Alval.allocate(_Count);

                _TRY_BEGIN
                _Umove(begin(), end(), _Ptr);
                _CATCH_ALL
                this->_Alval.deallocate(_Ptr, _Count);
                _RERAISE;
                _CATCH_END

                size_type _Size = size();
                if (_Myfirst != 0)
                    {    // destroy and deallocate old array
                    _Destroy(_Myfirst, _Mylast);
                    this->_Alval.deallocate(_Myfirst, _Myend - _Myfirst);
                    }

    #if _HAS_ITERATOR_DEBUGGING
                this->_Orphan_all();
    #endif /* _HAS_ITERATOR_DEBUGGING */

                _Myend = _Ptr + _Count;
                _Mylast = _Ptr + _Size;
                _Myfirst = _Ptr;
                }
            }
    </ecode>