Follow Slashdot stories on Twitter

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Best and Worst Coding Standards? 956

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?"
This discussion has been archived. No new comments can be posted.

Best and Worst Coding Standards?

Comments Filter:
  • Keep it simple! (Score:0, Insightful)

    by Anonymous Coward on Sunday July 20, 2008 @09:30AM (#24261641)
    Make it "cut and paste" friendly, and as small as possible.
  • Re:braces (Score:4, Insightful)

    by Splab ( 574204 ) on Sunday July 20, 2008 @09:42AM (#24261709)

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

  • by Anonymous Coward on Sunday July 20, 2008 @09:42AM (#24261711)

    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

  • Re:braces (Score:5, Insightful)

    by heffrey ( 229704 ) on Sunday July 20, 2008 @09:47AM (#24261749)

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

  • developer buy-in (Score:5, Insightful)

    by Dionysus ( 12737 ) on Sunday July 20, 2008 @09:48AM (#24261765) Homepage

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

  • Re:Keep it simple! (Score:5, Insightful)

    by bondsbw ( 888959 ) on Sunday July 20, 2008 @09:49AM (#24261771)

    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.

  • Re:braces (Score:2, Insightful)

    by LEMONedIScream ( 1111839 ) <<lemonjellly> <at> <gmail.com>> on Sunday July 20, 2008 @09:50AM (#24261773)

    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?

  • Re:braces (Score:2, Insightful)

    by __aapbzv4610 ( 411560 ) on Sunday July 20, 2008 @09:53AM (#24261791)

    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.

  • Re:braces (Score:3, Insightful)

    by __aapbzv4610 ( 411560 ) on Sunday July 20, 2008 @09:56AM (#24261807)

    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.

  • Re:braces (Score:3, Insightful)

    by DaveV1.0 ( 203135 ) on Sunday July 20, 2008 @09:56AM (#24261811) Journal

    Not them, and that is a good enough reason.

  • Re:braces (Score:5, Insightful)

    by thogard ( 43403 ) on Sunday July 20, 2008 @09:58AM (#24261817) Homepage

    The code is important. The braces are syntactical sugar.

  • Re:braces (Score:3, Insightful)

    by __aapbzv4610 ( 411560 ) on Sunday July 20, 2008 @10:01AM (#24261837)

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

  • Re:braces (Score:4, Insightful)

    by DaveV1.0 ( 203135 ) on Sunday July 20, 2008 @10:02AM (#24261845) Journal

    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.

  • Re:braces (Score:2, Insightful)

    by Anonymous Coward on Sunday July 20, 2008 @10:03AM (#24261857)

    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.

  • GNU Indent (Score:4, Insightful)

    by Jim Hall ( 2985 ) on Sunday July 20, 2008 @10:04AM (#24261861) Homepage

    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.

  • Re:My new standard (Score:3, Insightful)

    by Southpaw018 ( 793465 ) * on Sunday July 20, 2008 @10:08AM (#24261901) Journal
    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.
  • Re:braces (Score:5, Insightful)

    by TheRaven64 ( 641858 ) on Sunday July 20, 2008 @10:13AM (#24261921) Journal

    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.

  • Re:Keep it simple! (Score:5, Insightful)

    by superid ( 46543 ) on Sunday July 20, 2008 @10:13AM (#24261923) Homepage

    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.

  • Correct focus (Score:5, Insightful)

    by QuietLagoon ( 813062 ) on Sunday July 20, 2008 @10:15AM (#24261937)
    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.

  • by jrumney ( 197329 ) on Sunday July 20, 2008 @10:17AM (#24261949)

    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.

  • Re:braces (Score:2, Insightful)

    by tolomea ( 1026104 ) on Sunday July 20, 2008 @10:18AM (#24261961)

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

  • Re:Keep it simple! (Score:4, Insightful)

    by StrawberryFrog ( 67065 ) on Sunday July 20, 2008 @10:19AM (#24261971) Homepage Journal

    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.

  • Re:braces (Score:2, Insightful)

    by Splab ( 574204 ) on Sunday July 20, 2008 @10:22AM (#24262005)

    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.

  • Re:braces (Score:4, Insightful)

    by harry666t ( 1062422 ) <harry666t@DEBIANgmail.com minus distro> on Sunday July 20, 2008 @10:24AM (#24262023)
    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,
              }
  • Re:braces (Score:2, Insightful)

    by thogard ( 43403 ) on Sunday July 20, 2008 @10:27AM (#24262045) Homepage

    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.

  • by khendron ( 225184 ) on Sunday July 20, 2008 @10:30AM (#24262069) Homepage

    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.

  • Re:braces (Score:5, Insightful)

    by aj50 ( 789101 ) on Sunday July 20, 2008 @10:32AM (#24262081)

    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.

  • by Shados ( 741919 ) on Sunday July 20, 2008 @10:35AM (#24262113)

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

  • Re:braces (Score:2, Insightful)

    by tolomea ( 1026104 ) on Sunday July 20, 2008 @10:35AM (#24262117)
    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
  • by Anonymous Coward on Sunday July 20, 2008 @10:37AM (#24262125)

    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.

  • Re:braces (Score:1, Insightful)

    by Anonymous Coward on Sunday July 20, 2008 @10:50AM (#24262263)

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

  • by Fallen Andy ( 795676 ) on Sunday July 20, 2008 @10:50AM (#24262265)
    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

  • Re:braces (Score:5, Insightful)

    by Southpaw018 ( 793465 ) * on Sunday July 20, 2008 @10:54AM (#24262305) Journal
    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!). :)
  • by WPIDalamar ( 122110 ) on Sunday July 20, 2008 @10:58AM (#24262337) Homepage

    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.

  • Re:braces (Score:3, Insightful)

    by oddsends ( 867975 ) on Sunday July 20, 2008 @11:06AM (#24262431) Homepage
    Now tell me, those studies refer to the readbility of the english language, not a given computer language, right?
  • Re:braces (Score:4, Insightful)

    by Anonymous Coward on Sunday July 20, 2008 @11:15AM (#24262509)

    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.

  • by DeKO ( 671377 ) <danielosmariNO@SPAMgmail.com> on Sunday July 20, 2008 @11:21AM (#24262565)

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

  • Re:Correct focus (Score:3, Insightful)

    by pz ( 113803 ) on Sunday July 20, 2008 @11:27AM (#24262601) Journal

    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.

  • by Bloater ( 12932 ) on Sunday July 20, 2008 @11:38AM (#24262697) Homepage Journal

    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.

  • by vadmot ( 1329335 ) on Sunday July 20, 2008 @11:40AM (#24262711) Homepage
    Just read the classics for the best

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

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

    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 [microsoft.com]

    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.

  • by DrYak ( 748999 ) on Sunday July 20, 2008 @11:49AM (#24262773) Homepage

    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.

  • by Maxmin ( 921568 ) on Sunday July 20, 2008 @11:52AM (#24262791)

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

  • Re:braces (Score:1, Insightful)

    by Anonymous Coward on Sunday July 20, 2008 @11:56AM (#24262827)

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

  • by CastrTroy ( 595695 ) on Sunday July 20, 2008 @12:22PM (#24263073)
    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.
  • by Anonymous Coward on Sunday July 20, 2008 @12:26PM (#24263113)

    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.

  • Re:braces (Score:2, Insightful)

    by sideswipe76 ( 689578 ) on Sunday July 20, 2008 @12:26PM (#24263115)
    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.
  • by bperkins ( 12056 ) on Sunday July 20, 2008 @12:28PM (#24263147) Homepage Journal

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

  • Re:Embedded Coding (Score:3, Insightful)

    by trompete ( 651953 ) on Sunday July 20, 2008 @12:31PM (#24263183) Homepage Journal

    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.

  • Re:braces (Score:3, Insightful)

    by WGR ( 32993 ) on Sunday July 20, 2008 @12:34PM (#24263225) Journal

    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?

  • by gfody ( 514448 ) on Sunday July 20, 2008 @01:04PM (#24263569)

    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.

  • by Anonymous Coward on Sunday July 20, 2008 @01:09PM (#24263635)

    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.

  • by lawpoop ( 604919 ) on Sunday July 20, 2008 @01:28PM (#24263825) Homepage Journal
    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.
  • by harlows_monkeys ( 106428 ) on Sunday July 20, 2008 @02:33PM (#24264415) Homepage
    When doing maintenance on someone else's code, use their style, even if it is one you hate.
  • Re:braces (Score:2, Insightful)

    by D-Cypell ( 446534 ) * on Sunday July 20, 2008 @02:52PM (#24264591)

    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.

  • Re:braces (Score:4, Insightful)

    by D-Cypell ( 446534 ) * on Sunday July 20, 2008 @03:17PM (#24264795)

    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.

  • by Doctor Crumb ( 737936 ) on Sunday July 20, 2008 @03:33PM (#24264935) Homepage

    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.

  • by SuperKendall ( 25149 ) on Sunday July 20, 2008 @04:24PM (#24265355)

    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.

  • by kramulous ( 977841 ) * on Sunday July 20, 2008 @05:07PM (#24265659)
    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.

  • by telbij ( 465356 ) on Sunday July 20, 2008 @05:25PM (#24265789)

    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

  • by heroine ( 1220 ) on Sunday July 20, 2008 @05:45PM (#24265935) Homepage

    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.

  • by YourExperiment ( 1081089 ) on Sunday July 20, 2008 @06:15PM (#24266205)
    Looks to me like you should take up Python. :)
  • by Jesus_666 ( 702802 ) on Sunday July 20, 2008 @06:21PM (#24266237)
    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.
  • by Maxmin ( 921568 ) on Sunday July 20, 2008 @06:21PM (#24266245)

    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.

  • by Jesus_666 ( 702802 ) on Sunday July 20, 2008 @06:23PM (#24266263)
    Funny? Insightful! Python is the language I would love to like.
  • by Doctor Crumb ( 737936 ) on Sunday July 20, 2008 @08:09PM (#24267219) Homepage

    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?

  • by enoz ( 1181117 ) on Sunday July 20, 2008 @08:10PM (#24267231)

    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.

  • by telbij ( 465356 ) on Sunday July 20, 2008 @10:30PM (#24268545)

    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.

  • by fishbowl ( 7759 ) on Monday July 21, 2008 @04:15AM (#24270711)

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

  • by Rysc ( 136391 ) * <sorpigal@gmail.com> on Monday July 21, 2008 @06:30AM (#24271421) Homepage Journal

    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.

So you think that money is the root of all evil. Have you ever asked what is the root of money? -- Ayn Rand

Working...