Slashdot Mirror


Bad Programming Habits We Secretly Love (infoworld.com)

snydeq writes: Breaking the rules can bring a little thrill — and sometimes produce better, more efficient code. From the article: 'The rules are more often guidelines or stylistic suggestions, not hard-and-fast rules that must be obeyed or code death will follow. Sure, your code might be ridiculed, possibly even publicly, but the fact that you're bucking conventions adds a little bit of the thrill to subverting, even inadvertently, what amounts more often than not to the social mores of pleasant code. To make matters more complex, sometimes it's better to break the rules. (Shhhh!) The code comes out cleaner. It may even be faster and simpler.' What bad programming habits can't you (or won't you) break?

76 of 497 comments (clear)

  1. You're the problem by U2xhc2hkb3QgU3Vja3M · · Score: 5, Insightful

    If you think it's nice to break habits or do unconventional code just for the thrill of it, remember how fun it is when you need to work on someone else's code.

    1. Re:You're the problem by tripleevenfall · · Score: 4, Insightful

      “Any fool can make a rule
      And any fool will mind it.”

      Thoreau

    2. Re:You're the problem by invictusvoyd · · Score: 2

      âoeAny fool can make a rule And any fool will mind it.â

      Only a fool will not attempt to logically circumvent it

      _____________________________________
      live long and prosper ... sniff

    3. Re:You're the problem by Anonymous Coward · · Score: 4, Funny

      Back during Y2K updates to our code base, we'd occasionally have to deal with code written by an ex-employee, who we'll call John. It was so bad that every time someone opened a file he had worked on you'd hear a loud "FUCK! Another John file!" over the cubical walls.

    4. Re:You're the problem by Dutch+Gun · · Score: 4, Insightful

      I've heard arguments against writing proper comments similar to what the author makes: "but if you change the code and the documentation or comments don't change, then it might be worse than no documentation at all." My response is that if you're not updating the documentation or comments, then you're not finishing the job you were assigned. You could make the same arguments against taking the time to create meaningful variables and function names.

      There's another argument against comments I occasionally hear as well, which is "a competent coder should be able to discern what the code is doing without comments." While that's technically true, it's another argument I would reject. I feel the best comments can and should declare the intent of a block of code, rather than drilling down into the mechanics of the code. Those types of comments are often much more valuable than comments which simply regurgitate the mechanics of code in English.

      Still, in my own code, I don't have a fixed ratio of comment to code. It's entirely dependent on the complexity / obviousness of the code in question. For instance, if you have a very simple function, such as a handler that reacts to some UI event and just passes along the event to some other system, or performs a simple operation, it's stupid to spend a bunch of time and create excess visual noise to document that function. A quick glance at the code tells you everything you need to know about what's going on far easier than comment blocks.

      On the other hand, when code gets more complex, or the internal workings of a function is less than trivial, I expect to see a more comments in the code. In some of the most complex code I've either written or worked on, the number of lines of comments can actually exceed the number of lines of code. I've even seen some helpful little ASCII drawings in some particularly complex physics code, which was awesome.

      --
      Irony: Agile development has too much intertia to be abandoned now.
    5. Re:You're the problem by rgmoore · · Score: 4, Insightful

      I feel the best comments can and should declare the intent of a block of code, rather than drilling down into the mechanics of the code.

      Exactly. There's a lot of code that needs comments like "fixes bug XXX". If you had to fix a nasty bug and it took you a day to get the details right, let the next poor sap know what you were doing. Otherwise, he's likely to reintroduce the bug by tearing out this apparently useless code.

      Another good use of comments is to summarize a large block of code so that people don't have to dig into it to figure out what it does. For example, it's good to document functions at the top with enough detail that somebody would know how and when to call them without having to read through the whole thing.

      --

      There's no point in questioning authority if you aren't going to listen to the answers.

    6. Re:You're the problem by Jaime2 · · Score: 2

      If you need comments to know who wrote what and on what date, then you need to get your code into source control.

    7. Re:You're the problem by Anonymous Coward · · Score: 2, Interesting

      This. It's not about YOUR code, it's about the poor beggar who gets to try and debug it at 3am when it breaks. After it's been maintained for 3 years. By hordes of other programmers with indeterminate skills, most of whom took their stylistic cues from you. And still has your name all over it.

      There are very few circumstances under which a marginal boost in efficiency is preferable to code that's easy to maintain. Stylistic rules are there for reasons - and "efficiency" isn't one of them.

    8. Re:You're the problem by Translation+Error · · Score: 4, Funny

      Any fool can see that.

      --
      When someone says, "Any fool can see ..." they're usually exactly right.
    9. Re:You're the problem by Anonymous Coward · · Score: 3, Interesting

      Used judiciously, a goto can save a lot of trouble. The three use cases I have for occasionally using a goto are to break from nested loops, to break from a switch-case within a loop, or as part of error-handling routine where an exception-based approach are not possible or not permitted. In all cases, these are within the scope of a single function.

    10. Re:You're the problem by DutchUncle · · Score: 2

      No, it's not about who wrote what, it's about "This is to satisfy requirement X", followed by "VP Blow wants the color changed", "VP Schmoe wanted it changed back" . . . .

    11. Re:You're the problem by ralphsiegler · · Score: 3, Insightful

      That's n00b level confusing for the maintainer, arithmetic three pronged IF are still supported for the true ForTran (-- and note old skool spelling yo!) connioseur: IF (J-3) 204, 512, 123

    12. Re:You're the problem by coats · · Score: 3, Informative
      Donald Knuth has stated that he is in favor of these kinds of "structured GOTO's".

      There is a theorem that in general, GOTO's can be replaced by WHILE's and flags. What is generally not mentioned is that in the general case, the size of the resulting code grows exponentially in terms of the size of the original code. ;-(

      As it happens, we do not get exponential growth for the "break out of the loop" cases...

      --
      "My opinions are my own, and I've got *lots* of them!"
    13. Re:You're the problem by omnichad · · Score: 2

      Real programmers use 11101011 (on x86).

    14. Re:You're the problem by Actually,+I+do+RTFA · · Score: 3, Insightful

      That's only an admonishment against following bad rules. Thoreau practiced a lot of civil disobedience. Hell, he wrote the seminal work on the subject, a little essay titled "Civil Disobedience."

      Or, in the words of his contemporary and mentor:

      A foolish consistency is the hobgoblin of little minds.

      If a rule is bad, change it. But ignoring it while leaving it on the books is poor form.

      --
      Your ad here. Ask me how!
    15. Re:You're the problem by AmiMoJo · · Score: 2, Interesting

      We had a contractor I'll call Paul. He wrote exactly to spec, and not a line more. If you didn't say "protect against buffer overflows when accepting user input" you can guarantee his code would crash if you input a single extra character beyond the prescribed format. It only worked if you did exactly what the user manual described. Any slight deviation and you were screwed, often in ways that were not immediately obvious.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    16. Re:You're the problem by Anonymous Coward · · Score: 2, Insightful

      Not necessarily. Often rules designed to be rote-learned by beginners to keep them out of trouble and thus are kind of a generalized compromise. If you understand WHY a rule exists you can determine if it applies to a given situation and follow or disregard it accordingly.

      The rule still must stay on the books for people who don't have that expertise or motivation to learn the "why".

    17. Re:You're the problem by Spaham · · Score: 3, Funny

      yeah, Knuth is always your go to guy...

    18. Re:You're the problem by Existential+Wombat · · Score: 2

      Real programmers use 0001 (on PDP-11)

    19. Re:You're the problem by complete+loony · · Score: 2

      Tracking when changes were made, and why, is the job of your source control system. Describing what the code does, is mostly the job of the code; variable names, function names and an occasional brief comment. Describing the expected inputs and outputs of the code is the job of unit testing. Describing the intent of the code, well that's a bit harder to get the right balance. Of course there's lots of overlap, and some huge grey areas.

      When reading someone else's code to track down a bug, or add a new feature. I can understand what the code is doing by reading it or debugging it. I can discover who and when from source control. Perhaps cross referencing to extra information in a bug tracker. The hardest bit is discovering what the true intent of the code is supposed to be. That's where comments are the most useful.

      --
      09F91102 no, 455FE104 nope, F190A1E8 uh-uh, 7A5F8A09 that's not it, C87294CE no. Ah! 452F6E403CDF10714E41DFAA257D313F.
    20. Re:You're the problem by flargleblarg · · Score: 3, Funny

      “Hello, GOTO. My name is Inigo Montoya. You killed my father. Prepare to die.”

    21. Re:You're the problem by KGIII · · Score: 2

      10 GOTO 20
      15 ? "THIS LINE IS USELESS"
      20 RETURN

      Yes, yes I did eventually hire professionals. No, no they did not need my help.

      --
      "So long and thanks for all the fish."
    22. Re:You're the problem by jandersen · · Score: 4, Funny

      ...who we'll call John...

      ...a contractor I'll call Paul

      Right, so who's going to come up with George and Ringo to make up the full set?

    23. Re:You're the problem by martin-boundary · · Score: 2
      Meh, that ship has sailed. All modern programs are full of GOTOs. They're just called EXCEPTIONs.

      An exception is a nonlocal jump, where the destination is in some totally unrelated section of the codebase, typically written by some other programmer even. Everything that's said to be wrong with GOTOs is often said to be right by exception supporters.

    24. Re:You're the problem by Hognoxious · · Score: 2

      Half a million Rupees. Paul my ass, we all know he was called Palanduran.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  2. "The code comes out cleaner"? by PacoSuarez · · Score: 5, Insightful

    If the code comes out cleaner, you didn't break any of my rules. The rule "make the code as clean as possible" trumps all other rules.

    1. Re:"The code comes out cleaner"? by EllisDees · · Score: 5, Funny

      Does it trump the "make the code work" rule?

      --
      -- Give me ambiguity or give me something else!
    2. Re:"The code comes out cleaner"? by nitehawk214 · · Score: 4, Informative

      I would not consider non-working code as clean.

      --
      I'm a good cook. I'm a fantastic eater. - Steven Brust
    3. Re:"The code comes out cleaner"? by mattventura · · Score: 4, Insightful

      But sometimes you get awful, poorly thought out "style" guides like PEP8 that in many situations result in less-readable code. Go try lining up colons in a dictionary definition for the purpose of readability and see how it likes it. So actual readability gets thrown out in favor of some feel-good style guide.

    4. Re:"The code comes out cleaner"? by Mikkeles · · Score: 5, Funny

      Ah, the "No True Clean Code" fallacy.

      --
      Great minds think alike; fools seldom differ.
    5. Re:"The code comes out cleaner"? by phantomfive · · Score: 4, Insightful

      1) Make the code work
      2) Make the code readable
      4) Make the code flexible.

      --
      "First they came for the slanderers and i said nothing."
    6. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 2, Funny

      I try to keep to 80 rows. A little harder to read, but worth it.


      PS: MOOO YOU COW!

    7. Re:"The code comes out cleaner"? by aix+tom · · Score: 5, Interesting

      Having "taking over" a lot of code in my time, I can say for myself, having code that "works and I don't know why" makes me more nervous that code that "doesn't work and I don't know why".

      I'd rather have clean code, be it working or non working. If it's clean I can get it to work reasonably quick. If it's not clean and not working then I can easily justify a re-write. But if I can't understand it and it seems to be working, I always have the dread that someday it will break in a disastrous fashion in the most inconvenient of times with me being unable to do anything about it.

    8. Re:"The code comes out cleaner"? by viperidaenz · · Score: 2

      Must be a race condition. Did you follow the thread safety rules?

    9. Re:"The code comes out cleaner"? by Carewolf · · Score: 3, Funny

      1) Make the code work

      2) Make the code readable

      4) Make the code flexible.

      0) Make the code on time
      3) ???
      5) Make the code - PROFIT!

  3. It's a tradeoff by plover · · Score: 5, Insightful

    Sure, you can trade maintainability for efficiency and reliability. People do it all the time. You just have to understand the costs involved. If the efficient code gains you a million dollars in performance, maybe you can afford for it to be crappy code. Or maybe you'll be running the code for 10 years, and if it costs you $250,000 to keep a crusty old engineer on staff who can maintain it, suddenly that million dollars in performance may not be worth it.

    <disclaimer>I am a crusty old engineer.</disclaimer>

    --
    John
    1. Re:It's a tradeoff by JoeMerchant · · Score: 2

      I think he's saying that he costs $250K/year.

      I'm getting on toward old and crusty, and my cost to the company is certainly closer to $250K/yr than $25K/yr. Dunno what they pay the whelps coming out of school these days, but I never worked for $25K/yr after I got out of school.

    2. Re:It's a tradeoff by viperidaenz · · Score: 2

      If you get the million right now that may be worth spending 2.5 million over ten years, if you're short on cash flow. Going bankrupt is bad.

  4. Bad Habits? by CAOgdin · · Score: 2

    We ALL fully document our code, have clear specifications before we write code, use meaningful variable names and rely on IDEs...amirite?

    In my case, I only program (after doing it for pay for 45+ years) for myself, and I'm creating new stuff all the time, based on experience. For example, my backup strategy. It started out as a simple script to launch Drive Snapshot. It evolved, into having multiple, cascaded backups on one partition of the computer, which are replicated automatically to my main "server" in case the computer dies. Each computer in the office uses the same central repository. It's got bells and whistles that make my job a lot easier when I experiment...if I try some new app and it trashed Windows, I just roll back to last night's backup. (I believe in 100% backups of all computers...including the server...every night, and schedule "fixit/improve it" time first thing in the morning, so I can rollback and lose nothing.)

    So, personally, I now break all the rules, and let my needs dictate the code I write. It isn't specified, it's an evolving organism in my small environment.

    Oh, and I'm doing all that in cmd files...might consider upgrading to something exotic, like AutoIt, someday, but I've been saying that for four years now...

    1. Re:Bad Habits? by sconeu · · Score: 2, Funny

      I once saw source code for a library, written in Ada that had the following "feature".

      Since Ada code is "self documenting", each routine had a block comment documenting said routine. The block comment was LITERALLY a copy of the routine, commented out...

      e.g.:


      -- procedure body f is
      -- begin
      --TEXT_IO.PUT_STRING('Hello world');
      --TEXT_IO.PUT_LINE;
      -- end f;
      procedure body f is
      begin
      TEXT_IO.PUT_STRING('Hello world');
      TEXT_IO.PUT_LINE;
      end f;

      --
      General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
  5. Copy and Paste. by jellomizer · · Score: 4, Informative

    Sometimes I will copy and paste a function and just do some minor tweaks were I could have just added a parameter.
    Why do I do this? Readability. Having a function called SplitPersonName(string name) and another one called SplitCompanyName(string name) So when I run the function it will be easily readable, as well if there is a bug in one of the fuctions but it works fine for the other. I can just change that one function without having to unit test other parts that could have been effected.

    Also I avoid too much Classes that are extended from other classes, that tends to add confusion on where a particular code is being called if you are debugging it from the middle of the class structure.

    It is OK to break rules, but you should have a good reason to do so. Also you should feel free to not break the rules when you do not have a good reason to do so.
     

    --
    If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    1. Re:Copy and Paste. by Junta · · Score: 3, Insightful

      Adding another variant, when you have an existing function that you never expected to reuse part of, suddenly interested in a twist on it. The 'proper' answer is to refactor so that it is shared code, but the code being reused is something that's not changed in 3 years and never had an issue under impressive load. So I could either refactor including changing working code, or duplicate. I'll duplicate. Now my duplicate may break out the relevant code so that if such a circumstance arise later, that the duplication won't happen twice, but I would rather a duplicate exist than risk any change to proven code.

      --
      XML is like violence. If it doesn't solve the problem, use more.
    2. Re:Copy and Paste. by Junta · · Score: 4, Insightful

      Also agreed about too many classes. People think they make nice modular things by having short classes, but I just went through an exercise of pouring through about a dozen mind numbingly tedious files to find the single line of code that actually did something rather than just do a few pointlessly segregated checks or providing an alternative function for what '+=' already did or coercion into some datatype only to have it coerced back 'just in case' that middle layer might one day have another developer that would naturally think of it another way...

      --
      XML is like violence. If it doesn't solve the problem, use more.
    3. Re:Copy and Paste. by CastrTroy · · Score: 4, Insightful

      For any rule you can come up with, you can probably find a valid case where breaking the rule would result in better code. Even GoTo can be useful in certain circumstances. Most of the good uses of GoTo have been codified using other key words. .C# has the continue keyword. It's basically exactly the same as using a GoTo to skip processing the current item. GoTo would have accomplished the exact same task, but people have such a dislike of GoTo that they had to create a whole other keyword that does exactly the same thing.

      --

      Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
    4. Re:Copy and Paste. by PRMan · · Score: 3, Interesting

      But continue is very clear, as is break and return. Goto could go anywhere in theory, so it slows you down as you scan around looking for it.

      --
      Peter predicted that you would "deliberately forget" creation 2000 years ago...
    5. Re:Copy and Paste. by sandytaru · · Score: 2

      Just put a note to yourself in both places where you copied the code that you DO have the function duplicated elsewhere, so if you ever have to change it in one place, you know to check and verify you do or don't also have to check it on the other place. A dev at my last job who duped some code that would create a PDF out of a Word document with mad-libbed bookmarks from the customer's file forgot to leave himself a breadcrumb trail. Took us two weeks to chase those bugs down until he remembered.

      --
      Occasionally living proof of the Ballmer peak.
    6. Re:Copy and Paste. by jeremyp · · Score: 2

      This is the reason why you have comprehensive unit tests. You can refactor the original function safely in the knowledge that, if you break it, the unit tests will start failing.

      You do have comprehensive unit tests?

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    7. Re:Copy and Paste. by tommeke100 · · Score: 2

      Obviously you should have used the Factory Pattern in conjunction with the Strategy and Visitor Pattern. It would have been way more verbose, more complicated to read and probably a few cpu cycles slower per call, but you would have looked so much smarter :)

    8. Re:Copy and Paste. by Darinbob · · Score: 2

      Envelopes stuffed into envelopes which are stuffed into envelopes, which are stuffed into manila folders which are stuffed into binders, which are stacked into cabinets, which have a security guard standing in front with orders to shoot anyone looking suspicious.

    9. Re:Copy and Paste. by readin · · Score: 3, Insightful

      Unit tests are no match for years of reliable service because for useful programs there is no such thing as a comprehensive unit test. One of the reasons computers are so useful is they can handle so many different input values - so many that you can't possibly test them all. Want to test a '+' operator for integers? Unless you run all MAX_INT * MAX_INT (oh way, I mean MAX_INT - MIN_INT+1 * MAX_INT-MIN_INT +1) possible inputs, how can you be sure you got everything? Well, let's just pick a representative test. Oh wait, we need to make sure we try with a negative number. Oh yeah, we need to a negative+negative, a positive+positive, a positive+negative, and a negative+positive. That it? Oh yeah we need to try negatives positives with zeros too. NOW we're done. What? OOHHH overflow! We need to write a test for two very large positive numbers and another for two very large negative numbers!

      That's just for simple integer addition. When you start writing real-life code the combinations of inputs grow very quickly. You do your best, but it simply isn't practical to test for every possible thing that could cause a problem.

      --
      I often don't like the choices people make, but I like the fact that people make choices. That's why I'm a conservative.
  6. Documentation by PvtVoid · · Score: 5, Funny

    From TFA:

    my friend wired together an Eliza-like AI to his editor, and voilà, every function had a few lines of "documentation." The boss wasn't smart enough to understand that the lines meant nothing, so my friend was off the hook. His code was officially documented. I think he even got a promotion!

    He should have been shot.

    1. Re:Documentation by amicusNYCL · · Score: 5, Insightful

      The boss or the developer?

      Yes.

      --
      "Our two-party system is like a bowl of shit looking at itself in a mirror." - Lewis Black
    2. Re:Documentation by jeremyp · · Score: 3, Interesting

      The functionality of a non private API must be documented. Requiring people to read the code in a function in order to find out what it is supposed to do is stupid.

      If a programmer changes the code in a function such that its API documentation is wrong, the documentation hasn't gone stale, the programmer introduced a bug.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
  7. long methods and coupling by Anonymous Coward · · Score: 5, Insightful

    long methods - someone thought it a good idea to limit every method to no more than 20 lines. I think this is a terrible idea, and can make code unreadable, which leads to:
    coupling - it's often best to tightly couple things for ease of debugging and development. How often are you going to change the database you're using? Is it worth going through another abstraction for every database call? Too much abstraction makes code unwieldy.

    I'd rather have a bunch of 200 line methods that represent logical units of work than a call stack 20 layers deep.

    1. Re:long methods and coupling by coats · · Score: 2
      Two points: experimental, and cognitive Experimental: the evidence shows that the minimum bug-rate occurs for methods of somewhere between 300 and 500 lines. More than that and it really is too complicated to comprehend, most of the time. Less than that and you think "It's simple" and don't pay proper attention. Cognitive: magic numbers
      • 2 - 3 is the number of levels of recursion you can keep in your head at one time. Nested logic structures and call-stacks should never require you to look more than 3 levels deep to understand them.
      • 6 - 7 is the number of distinct objects you can keep in your head at one time. Never require that the reader keep track of more than that. If you think you need to, it means you haven't properly thought out your problem yet.

      Side-note: Names that are too long fall afoul of the same effect: they force you to concentrate on how to read the name, rather than what the object means. Complex names should only be used for rarely-touched global entities; local scratch-variable names should be shorter -- the extreme being single-letter "i" for loop counters:

      for( int i=0 ; i<dingbat_max ; i++ ) {...

      --
      "My opinions are my own, and I've got *lots* of them!"
  8. GOTOs in C by Anonymous Coward · · Score: 2, Interesting

    I often use GOTO statements in C code to mimic exception catching without duplicating cleanup code. It works very well, and its easy to understand, maintain, and debug. Example:

    x = do_stuff();
    if (x 0) { goto cleanup; }

    y = do_more stuff();
    if (y 0) { goto cleanup; }
    return 1;

    cleanup:
    fix_my_mess();
    fix_it_4realz();
    return 0;

    1. Re:GOTOs in C by halivar · · Score: 5, Interesting

      Comp Sci professors teach "goto = bad" because the wisdom necessary to use it competently comes only with experience. It's like jazz; you have to know the rules and follow them before you can break them and not sound like a jack-ass.

    2. Re:GOTOs in C by JustNiz · · Score: 3, Insightful

      Wow. WAY too much code for what it actually needs to be. Furthermore the fix functions have now leaked scope all the way to main().

    3. Re:GOTOs in C by PRMan · · Score: 2, Interesting

      void cleanup()
      {
      fix_my_mess();
      fix_it_4realz();
      }
      ...
      x = do_stuff();
      if (x == 0){
      cleanup();
      return 0;
      }

      y = do_more_stuff();
      if (y == 0){
      cleanup();
      return 1;
      }
      return 0;

      --
      Peter predicted that you would "deliberately forget" creation 2000 years ago...
    4. Re:GOTOs in C by halivar · · Score: 3, Insightful

      So far we have 3 comments with the "right" way to do it that do nothing but add complexity and loss of readability for strict adherence to dogmatism imparted by our CS professors (few of whom had real-world programming experience).

      This is a straightforward problem. The suggested use of goto is a straightforward solution, and cleaner by far than the suggested alternatives. But most importantly, no one can demonstrate how it is wrong.

    5. Re:GOTOs in C by flargleblarg · · Score: 2

      The top code is more fragile. And you also end up repeating all the cleanup code, often several times. In the bottom code, it's all nicely and neatly in one place...much more maintainable.

  9. Dijkstra Nailed It by myrdos2 · · Score: 5, Insightful

    In short, I suggest that the programmer should continue to understand what he is doing, that his growing product remains firmly within his intellectual grip. It is my sad experience that this suggestion is repulsive to the average experienced programmer, who clearly derives a major part of his professional excitement from not quite understanding what he is doing. In this streamlined age, one of our most undernourished psychological needs is the craving for Black Magic and apparently the automatic computer can satisfy this need for the professional software engineer, who is secretly enthralled by the gigantic risks he takes in his daring irresponsibility. For his frustrations I have no remedy......

    --Edsger W. Dijkstra

  10. Lessons by Tablizer · · Score: 5, Interesting

    Variable and object naming, and commenting is an art-form that takes experience to do well. Here's a few practical guidelines I've learned follow:

    1. Think of newspaper headlines when commenting. Don't make somebody read the whole article to know what the article is about.

    2. Comment the "odd" stuff, not the obvious stuff infer-able from function name etc.

    3. Goldilocks Rule: Names both too long and too short can be bad.

    4. The more frequent a name is used, the shorter it should be. Use comments at declaration to give the full name. Example of a variable that may be used often:

    var dhv_id; // Department of Housing vendor ID

    If it's used often, I'd rather have an abbreviation than see DeptOfHousingVendorID all over the code, making it long and "wrappy".

    5. Everybody has their own preference, but you have to target the "average" developer (future unknown reader) to make code future-friendly.

    1. Re:Lessons by dark.nebulae · · Score: 3, Insightful

      I've been programming for quite awhile and honestly I'm in the verbose commenting camp.

      Not because I'm worried about code reviews, handing the code off to anyone else or even following some company's arbitrary rules on how things should be documented.

      I use verbose comments so I don't have to remember what was done and why it was done that way. Frankly I've got too many other things that I'd rather remember.

      Granted verbose comments will make my code seem pretty old school, but I have yet to hear any questions from someone who picked up my code after I've left it.

      And I can go back to code and know what I was doing even if it was 5 years ago. Now I may laugh at myself and be amazed at just how much I didn't know even then, but I will totally understand what's in the code without having to guess.

    2. Re:Lessons by internerdj · · Score: 5, Funny

      "Think of newspaper headlines when commenting. Don't make somebody read the whole article to know what the article is about." You_won_t_believe_the_three_things_this_method_does(), This_method_just_announced_it_was_running_for_the_GOP_presidential_nomination(unsigned int year), Five_ways_to_make_your_integers_long(), ...

    3. Re:Lessons by Tablizer · · Score: 2

      Hungarian notation (HN) is controversial. If the variable's name is a sufficient clue to the type, I'd consider skipping HN.

      For example, "lineCount" is pretty obviously an integer, and invoiceAmt (or invoiceAmount) is obviously a monetary value (typically "double").

      I like to use "isX" for booleans, such as "isGood" for a quality check flag, or "isFinished" for a loop flag.

      They both have their trade-offs and it's probably a close call either way if done smartly.

    4. Re:Lessons by Tablizer · · Score: 2

      I meant real newspapers, not tabloids :-)

      (Do they still make those?)

      get_off_my_lawn(exclamation);

  11. One extra space per bracket by xxxJonBoyxxx · · Score: 2

    Just one extra (or fewer) space per bracket...'cause I know it's driven SOMEONE nuts at every shop I've worked at.

  12. The Issue with programming. by jellomizer · · Score: 4, Insightful

    We are hired to write new programs/new ways of solving a problem. Rules are made to solve common problems.
    If we only follow these rules we are limited to writing programs that have already been written, in that case we are just useless.
    If we know when to bend or break the rules, then we can create things that solve problems differently and is new and unique.

    When I work with programmers so are hard fixed on the right way to do things, I often get a response that x cannot be done. I break the rule and I have done it in a couple of days work, then they will go but you didn't follow the right form.
    The end user doesn't care about form, they care if it Works well, It can be maintained, and it is secure.

    --
    If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    1. Re:The Issue with programming. by Anonymous Coward · · Score: 3, Insightful

      You sound are one of the "men of some parts whose cleverness sets them apart from their fellows, but not nearly so far as they imagine."

      If we only follow these rules we are limited to writing programs that have already been written...

      Non sequitur, and nonsensical. All major programming languages are Turing-complete, and should all be able to express the same statements/programs.

      When I work with programmers so are hard fixed on the right way to do things, I often get a response that x cannot be done.

      There are things that are impossible in computer science, e.g. solving the Halting Problem. Most programmers tend not to conflate the impossible with the difficult or computationally expensive; your doing so is not a good sign. Probably you're just using hyperbole to exaggerate your own competence. If not, your coworkers are likely also dullards, or you solved a different problem, or you introduced a subtle bug. Either way, breaking rules and ignoring your coworkers is enough to classify you as a bad coder, and your command of the English language makes me doubt your abilities in any other.

      I'm guessing you're self-taught, and hoping you work mostly alone, and I pity people who use your code.

    2. Re:The Issue with programming. by silentcoder · · Score: 2

      Interesting how many of the "rules" are considered bad form in python (as one example) - and in fact following them is considered ugly, unmaintainable code. Then again, a lot of python rules specifically contradict the rules of everything that came before.
      A standard rule in every OOo course is that objects should not expose data, only methods for manipulating data - and the manipulation should be entirely confined to the class. Python considers getters and setters extremely bad form and insists that the variables be exposed directly instead (ruby sits in an odd place between those two views).
      Most OOo languages consider the split between public and private extremely important, python deliberately does not offer true private members (though it does offer a by-convention method of hinting to other coders that they shouldn't thoughtlessly access something).

      The "rules" say don't make your own data structures, but python not only encourages this - it makes it ridiculously simple to ensure your custom data structures remain entirely compatible with the system default versions, so that standard tools and operations can transparently work with them (magic methods to make your class behave like a list or an iterator or a generator for examples) - Ruby takes that a step further by actually allowing you to replace any data-structure with your own compatible version - and transparently do this into code that loads your library (personally I think that takes it a step too far - it allows for great transparency but it also means that other developers can be caught very off guard when what looks like a string doesn't BEHAVE like a string).

      So yeah, rules are generic but specific problems require specific solutions which may not always follow those rules, and more than that a - a lot of rules were based on hypotheses "we think if you do X then the effect will be Y" that was never subjected to the scientific method - and a lot programming languages have deliberately changed or abandoned those rules exactly because in practice they didn't work the way it was hypothesized and actually made code worse to read and maintain.

      --
      Unicode killed the ASCII-art *
  13. Re:Breaking out of the middle of a loop by PRMan · · Score: 4, Insightful

    He's still trotting out "rules" that were in vogue 15 years ago. Break, continue and early return are clean and inserted into every programming language eventually.

    --
    Peter predicted that you would "deliberately forget" creation 2000 years ago...
  14. can't code, afraid of disapproval by anyaristow · · Score: 4, Insightful

    It seems that many in the field these days are afraid to code something themselves for fear that someone will find fault. So, they do things "the established" way, which is generally frameworks or anything that can be called "reusable", even if this generation's "reusable" is always less reusable than last, because it keeps getting needlessly more complex to the point that nobody *can* reuse it.

    Used to be programmers had a fault we called "not invented here", in that they'd insist on re-writing things that already existed, because it was easier to understand their own code than to use someone else's. These days it's reversed. For fear of criticism, they *must* use someone else's code rather than write their own. I call it "afraid to invent it here."

  15. Re:goto by tlambert · · Score: 2

    Seriously people still use the goto statement and love it? I have never meet anyone that loved the goto statement.

    It's only loved by people who think functions should be single entry, single exit, so that you can wrap the code in asserts during testing so that you can be sure that you've got the right lock state on entry and exit. It's also great for detecting memory leaks.

    If you never use locks, or never had a lock leak, or never had a memory leak, or know bugger all about assembly (the compiler is going to emit the JMP instruction, whether you like it or not, and if you don't understand assembly, you should probably not be coding), then I guess avoiding "goto" and using all sorts of weird conditionals to break out of two or more nested loops would work for you.

  16. Re:All my indexes are i, j, k by default. by Anonymous Coward · · Score: 2, Funny

    It is actually a best practice. What I hate is seeing 'x' used for a discrete variable, or n for a float. Such people without regard for mathematical form should be shot.

  17. You need two expressions of intent to detect bugs. by Ungrounded+Lightning · · Score: 2

    There's another argument against comments I occasionally hear as well, which is "a competent coder should be able to discern what the code is doing without comments." While that's technically true, it's another argument I would reject.

    Me, too.

    Sure, a competent coder can tell what the code IS DOING. So can a compiler. That's not the issue. What do you do if what the code is doing is the wrong thing? What is the RIGHT thing? If all you've go is the code, you're hosed.

    NO process can look at code alone and find bugs - because correct code for one thing is not correct for another. A perfect implementation of "cat", for instance, is not correct when what you want is "echo". All correctness checking can do is compare two (or more) expressions of the intent for discrepancies.

    I feel the best comments can and should declare the intent of a block of code, rather than drilling down into the mechanics of the code.

    And that's what they're for. When writing multiple expressions of intent, the less similar the languages used are, the less likely an identical error will end up in all of them.

    With the comments you have a chance. With allegedly "self-documenting code" all you can test is the compiler.

    --
    Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way