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?

497 comments

  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: 0

      It's great fun. Challenges like that are what really allow us to grow as individuals.

      Anyway my favorites are to use strange naming conventions inside each scope, using 3-letter and vowel-less identifier names, and extensive networks of goto spaghetti.

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

    5. Re:You're the problem by Anonymous Coward · · Score: 0

      Enough of this foolishness!

    6. Re:You're the problem by Anonymous Coward · · Score: 0

      I put GOTOs in all of my programming. muwhahahaha.

    7. Re: You're the problem by Anonymous Coward · · Score: 0

      One project I worked on, I created a wrapper construct to help with some messaging abstraction. Well, another employee who worked on the same project decided he had to create his own personal wrapper around that. What a friggin mess.

    8. Re:You're the problem by sexconker · · Score: 1, Insightful

      There's nothing wrong with GOTOs.

    9. 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.
    10. Re:You're the problem by Hussman32 · · Score: 1, Interesting

      My comment about comments in code is that all comments need a date and the coder's initials as a minimum, and old comments should not be deleted. I have way too much experience knowing why these are my comments.

      --
      "Who are you?" "No one of consequence." "I must know." "Get used to disappointment."
    11. Re:You're the problem by stargazer1sd · · Score: 1

      Comments are most useful when talking about data and its semantics. For some reason, we've gotten so obsessed with the operations, we've forgotten that we're operating on data with real meanings that are usually left to some magic combination of guesswork and discernment.

      --
      Play it cool, play it cool, 50-50 fire and ice.
    12. 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.

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

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

    15. Re:You're the problem by Anonymous Coward · · Score: 0

      You haven't seen how I use them ;)

    16. Re:You're the problem by Jaime2 · · Score: 0

      Everything you say is correct. The question is whether a written policy will make the people you work with do it right, or will it make them write horrible and/or useless comments to satisfy the policy. In my experience the only way to turn a bad commenting programmer into a good commenting programmer is to regularly review their code and provide feedback.

      So, I'm not against comments, I'm against policies that enforce comments. Those policies rarely do more good than they do harm.

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

    19. Re:You're the problem by Anonymous Coward · · Score: 1

      A GOTO killed my father, you insensitive clod!

    20. Re:You're the problem by Anonymous Coward · · Score: 0

      You'd like Fortran. You can still use computed GOTOs, though they're now going to emit deprecated warnings from the compiler. Have fun debugging lines like GOTO 12, 43, 2, 125

    21. Re:You're the problem by U2xhc2hkb3QgU3Vja3M · · Score: 1

      1 GOTO 3
      2 GOTO 1
      3 GOTO 2

      That's how I tie my shoes.

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

      His method is perfectly sound if you need to work in an environment that does not have source control.

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

    24. Re:You're the problem by DutchUncle · · Score: 1

      Or chainsaws.

    25. Re:You're the problem by Anonymous Coward · · Score: 0

      "Rules were made to be broken, just like people!" -- Jinx, League of Legends.

    26. Re:You're the problem by Jaime2 · · Score: 1

      With the number of source control systems available, many completely free and many requiring no dedicated infrastructure, not having source control is something that happens mostly to those who think source control is worthless.

      There are some cases where source control is impractical - like when your code is embedded in something else. However, this is an exception, not the rule. Hussman32's statement was that "all comments need a date and the coder's initials as a minimum, and old comments should not be deleted". The statement was made as a general one - but it's only true in a limited number of edge cases.

    27. Re:You're the problem by U2xhc2hkb3QgU3Vja3M · · Score: 1

      Some systems cannot be used with source control systems since they operate completely internally.

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

    29. Re:You're the problem by Jaime2 · · Score: 1

      Yea, I said that. His statement is still only correct for a very small percentage of the people that might read it. That makes it a bad generalization.

    30. Re:You're the problem by Anonymous Coward · · Score: 0

      Do that naked through a field of dicks. Run backwards, I mean.

    31. Re:You're the problem by Anonymous Coward · · Score: 0

      There's nothing wrong with GOTOs.

      There is nothing wrong with the rule against gotos either.
      The point of those rules is to keep people from using powerful tools that they don't know how to handle.

      First you learn the rule. Don't break the rule until you understand why the rule is there to begin with, when you do you know how to avoid the pitfalls.

    32. Re:You're the problem by dreamchaser · · Score: 1

      There's nothing wrong with GOTOs.

      Correct, when used wisely, but real programmers use JMP instead (on x86/64).

    33. 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!"
    34. Re:You're the problem by Anonymous Coward · · Score: 0

      If your code flow is best explained with a flowchart instead of a rat's nest, then GOTO is appropriate. Any code that doesn't nest and has many decision branches is probably best done with GOTO. However, if you're iterating, GOTO is from ass, and you should have slapped yourself. However, for the "did I get this function insitialized correctly" and "let's see if the hardware powered up without breaking" then GOTO is proper.

    35. Re:You're the problem by Fwipp · · Score: 1

      git blame myfile

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

      Real programmers use 11101011 (on x86).

    37. 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!
    38. Re:You're the problem by Anonymous Coward · · Score: 0

      Ah, God bless you. That's the kind of thing I was meaning :) Solidly C++, with some F03, these days, and it all goes a bit dim in the mind.

    39. Re:You're the problem by Anonymous Coward · · Score: 0

      Yes, I can plainly see that.

    40. 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
    41. Re:You're the problem by Hussman32 · · Score: 1

      A lot of the code I worked on wasn't source controlled, and that was what I was thinking about with this note. Still, most source control systems are time-stamped with the user who made the change, and usually have a comment section for the changes. If you make a change to code, you should change the comments too, and also see a history of the changes. Sometimes the problem changes, sometimes the solution changes, and sometimes the talent changes. In all cases it helps to see who did what and why they did it at that time.

      --
      "Who are you?" "No one of consequence." "I must know." "Get used to disappointment."
    42. Re:You're the problem by CSMoran · · Score: 1

      Mr. Dengo was *the* GOTO, not *a* GOTO.

      --
      Every end has half a stick.
    43. 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".

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

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

    45. Re: You're the problem by Anonymous Coward · · Score: 0

      How do you know where the documentation is? Say you modify a function. Is the comment in the header file or the code file? Is it at the top of the function, the top of the class, the top of the file, or somewhere else entirely? Maybe it's in a summary readme, or a wiki, or somewhere else. It's often easy to miss a comment written by somewhere else because it could be anywhere.

    46. Re:You're the problem by rgmoore · · Score: 1

      Except that running git blame is an extra step compared to looking at a comment that's right next to the code. The more effort involved in figuring out what's going on, the lower the chance of somebody actually doing it.

      --

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

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

      Real programmers use 0001 (on PDP-11)

    48. Re:You're the problem by jonwil · · Score: 1

      +1 to this, comments should explain why the code does what it does, not just what it does.

    49. Re: You're the problem by Dutch+Gun · · Score: 1

      When I was talking about comments, I was mostly referring to comments that described the functionality of internal code. In these cases, the comments are typically embedded right with the code, so the locality of that sort of documentation isn't a problem.

      For external documentation... I think that would tend to be a per-company or per-project issue. If I was working on code that required external documentation, I'd generally recommend keeping it in the source files using Doxygen or something like that to auto-generate the documentation from specially-formatted comments. It seems a lot more practical to me to keep the documentation tied to the source code for precisely the reasons you imply - if it's separated, it's too easy to let them get out of sync.

      --
      Irony: Agile development has too much intertia to be abandoned now.
    50. 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.
    51. Re:You're the problem by Anonymous Coward · · Score: 0

      However, the git blame doesn't suffer the problem of becoming misleading because someone couldn't be bothered to update text which has zero impact on the final product. Comments require effort to maintain, so they often aren't.

    52. Re:You're the problem by flargleblarg · · Score: 3, Funny

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

    53. Re:You're the problem by Tablizer · · Score: 1

      There's a lot of code that needs comments like "fixes bug XXX".

      I don't know how many times I've written comments similar to:

      // Works around a bug in Microsoft X version Y.
      // I have no idea why this "fixes" it,
      // It just does.

    54. Re:You're the problem by tomhath · · Score: 1

      I hate looking at code with a bunch of commented out cruft and obsolete comments. It's a holdover from the days before real source control and should never be seen today.

    55. Re:You're the problem by Anonymous Coward · · Score: 0

      The point of those rules is to keep people from using powerful tools that they don't know how to handle.

      That's like inventing a tool, sharing it with anyone who wants it, and then bitching at them for using it.
      It's also elitist, smug, and ridiculous.

    56. Re:You're the problem by Anonymous Coward · · Score: 0

      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.

      I worked on a project around 2001 that was outsourced. Our version of John was named Seema Shetty,

      My office mate and I often said: Seema Shitty to you? Seema Shitty to me...

    57. Re:You're the problem by Anonymous Coward · · Score: 0

      > The point of those rules is to keep people from making easily preventable mistakes.

      There, FTFY.

      "Power" is not the equivalent of "easy to abuse." Yes, you can do things with GOTOs that you can't do with structured logic. No, you don't usually want to do those things. Structured code is your friend.

    58. Re: You're the problem by Anonymous Coward · · Score: 0

      Fucking hobgoblins

    59. 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."
    60. Re: You're the problem by Anonymous Coward · · Score: 0

      It's easy, but the call stack is all messed up

    61. Re:You're the problem by Anonymous Coward · · Score: 0

      He sounds like a model employee. He's probably making half a million a year now as a rockstar developer for some large corporation.

    62. Re:You're the problem by Anonymous Coward · · Score: 0

      Or even your own if you document what you did in a way your future self won't understand.

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

    64. Re:You're the problem by Anonymous Coward · · Score: 0

      If your programming language doesn't let you break out: refactor the block you want to break out of into a function, then use return.

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

    66. 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."
    67. Re:You're the problem by Anonymous Coward · · Score: 0

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

      That might make the other one Dzahn.

    68. Re:You're the problem by Anonymous Coward · · Score: 0

      So, the internals have room for a compiler, but not a source control system?

      And you can connect a keyboard and screen, but not a USB-stick to transfer data from you regular development system?

      Something smells fishy.

    69. Re:You're the problem by AmiMoJo · · Score: 1

      He was British. His favourite and most annoying habit was to use massive case statements to do cooperative multitasking. Each "task" would just be a function with a massive, numbered case statement and a counter that incremented by one in each case... Except where he wanted to use a "goto", and just assigned some random number to it. No #defined names of course, just numbers. Because fuck it, once it meets the spec he got paid and the worse the code was the more he would have to be paid to add additional features like "not crashing when the file is 1 byte longer than expected".

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

      I pity the fool !

    71. Re:You're the problem by Anonymous Coward · · Score: 0

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

      Offtopic but apropos: Second amendment to the US Constitution.

    72. Re:You're the problem by U2xhc2hkb3QgU3Vja3M · · Score: 1

      There's no compiler. The code is saved to a database, there's no individual files to backup.

    73. Re:You're the problem by Tablizer · · Score: 1

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

      A bunch of code Monkees

    74. Re:You're the problem by antdude · · Score: 1

      "Foolboys, be quiet." --my chicken. :P

      --
      Ant(Dude) @ Quality Foraged Links (AQFL.net) & The Ant Farm (antfarm.ma.cx / antfarm.home.dhs.org).
    75. Re:You're the problem by Anonymous Coward · · Score: 0

      In my experience, usually a double-break (your first two examples) are better implemented as having the outer loop factored into a function with an inline return (I also usually avoid inline returns, but this is the exception). A nested loop, or a switch inside of a loop, tends to be performing a single operation that makes logical sense as a function unto itself.

      I have seen the pseudo-exception-handling and I'm not in favour, in part because it makes debugging more difficult than when there is a single-exit (yes, your *function* has a single exit, but the interior of your function has multiple exits). I prefer triangular coding because it also helps to enforce minimal scoping and it makes clear where all the jumps are -- it's basically equivalent but your goto is hidden behind an if statement that visually displays the scope of the goto, and it prevents the possibility of accidentally entangling two cases that should logically nest. Error cascades read similarly to gotos but are also a little bit easier to deal with when debugging in my opinion, since you can more easily bisect a function to find where it failed out.

    76. Re:You're the problem by Aighearach · · Score: 1

      Luckily in this case we're only talking about conventions and recommendations, not rules. And they're not even bad ones, they just had context that was omitted. I certainly agree if you don't know the context of an engineering convention, it may not apply to you; you're better off trying to understand what the consideration teaches than to follow the recommendation directly. But keep it in mind later when things aren't going as smooth as expected, and maybe try it both ways. That is the beauty of software, compared to other types of engineering; it is easier to refactor a software function than a steel bridge.

      And bad habits wouldn't even be habits if the people doing it that way didn't like it better. It is a bad habit precisely because we'd rather do it that way, at least in the short term. Implied is that there is some other reason it doesn't work out later, so we refrain; and hopefully keep the love secret on account of having not actually written the code in the way that is predicted to suck later.

    77. Re: You're the problem by Anonymous Coward · · Score: 0

      lol I was gonna post that. Eat a rocket from across the map. Snipe snipe.

    78. Re: You're the problem by Anonymous Coward · · Score: 0

      Code beatles.

      FTFY.

      I always wanted to be a beatle - John Lennon

      We are missing Pete Best. Poor Pete.

    79. Re:You're the problem by Actually,+I+do+RTFA · · Score: 1

      Then, and I am serious, there should be rules about breaking rules. When I wrote a coding standard, I included the idea of which rules were to be followed (naming conventions, indentation) and which were guidelines that were assumed to be followed. The guidelines included justifications, so you knew why they applied. They were unbreakable by an intern (absent getting the okay from a permanent employee), and they generally required a comment explaining why you weren't following it if you did something unexpected.

      And I mean, even our "fucking indent the curly braces like this" line that every coding standard (in the Cxx world) needs had "unless you're working on an existing codebase clause.

      Hopefully including the justification made people better able to follow the guidelines when they made sense, and more comfortable when they did not.

      --
      Your ad here. Ask me how!
    80. Re:You're the problem by david_thornley · · Score: 1

      An exception is more of a come-from, but it fires only in exceptional circumstances (when written by competent people, anyway) when continuing isn't going to work. The destination is in the code that uses the part that throws, not some arbitrary code somewhere.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    81. Re:You're the problem by arglebargle_xiv · · Score: 1

      'The rules are more often guidelines or stylistic suggestions, not hard-and-fast rules that must be obeyed or code death will follow.

      "The Programmers Code is more what you'd call 'guidelines' than actual rules. Welcome about the Black Perl, Miss Turner...".

    82. Re:You're the problem by swilver · · Score: 1

      A comment like fixes bug XXX is useless -- instead, add a Unit test that verifies that bug XXX is fixed.

    83. Re:You're the problem by phantomfive · · Score: 1

      Nah, they're too busy singing to put anybody down.

      --
      "First they came for the slanderers and i said nothing."
    84. Re:You're the problem by jwhitener · · Score: 1

      the number of lines of comments can actually exceed the number of lines of code

      This should be the norm.

      Most people, especially those with less than 10-15 years experience, don't have experiences dealing with very old code. That code may have been written using a set of assumptions that don't even exist anymore. From dependency assumptions (of course service X will be running as long as this code runs) to business/logic assumptions (of course Sheryl in accounting will drop this data file in this folder every week).

      Pretend to be someone that doesn't know the business/process at all when writing comments. Pretend to be someone brand new 10 years from now when re-reading them for accuracy. Make a lot of "Why" comments, not just "How".

  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 Anonymous Coward · · Score: 0

      He said all other rules, so I would guess yes...

    4. Re:"The code comes out cleaner"? by DrTJ · · Score: 0

      It definitely Donald Trumps it!

    5. Re:"The code comes out cleaner"? by JustNiz · · Score: 1

      Yeah but none of the suggestions in the OTA actually make the code cleaner.

    6. Re:"The code comes out cleaner"? by JustNiz · · Score: 1

      Sorry I I have too many threads running in my brain. I meant TFA not OTA.

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

    8. Re:"The code comes out cleaner"? by PRMan · · Score: 1

      That's especially true of continue and break and early return. Those make code much cleaner and more readable.

      --
      Peter predicted that you would "deliberately forget" creation 2000 years ago...
    9. 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.
    10. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      It seems you don't get the joy of obfuscation. That's what I call fun.

    11. 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."
    12. Re:"The code comes out cleaner"? by pla · · Score: 1

      #2 means you don't end up with code like:
      a=b+c; // add 'c' to 'b' and store it in 'a'
      If you really needed that comment, turn in your geek badge now.

      #3 vastly improves readability in most cases. Trying to read through one statement per line feels like trying to read a book
      with
      one
      word
      per
      line.

      #4 means you don't need to tediously declare every loop variable. I don't care what type "i" has - If the original coder sucks so badly that a simple iterator breaks, I don't keep trying to read their code, I start rewriting it.

      #7 can make for far more readable code than deeply nested branching and complex loop conditions where a simple "return" or two would have made the code effectively flat and easily readable.

      #8 matters primarily in cultures guilty of the exact opposite... If you would otherwise need to scroll horizontally to fully see a line (egregious abuses of #3 aside)... Use shorter names!

    13. Re:"The code comes out cleaner"? by mark-t · · Score: 1

      Your example for #2 is only generally practicable if you want your comments to be compiled by a COBOL compiler.

    14. Re:"The code comes out cleaner"? by sexconker · · Score: 1

      I make sure my code fits in 80 columns max.
      I do comment blocks like a well-formatted readme.

      ////////////
      // Stuff! //
      ////////////
      i = 0;
      j = 1;
      dice = "trash";

      It pleasures the eyeballs. (There's no way slashdot would let me post it in full width.)

    15. Re:"The code comes out cleaner"? by JoeMerchant · · Score: 1

      I think there are instances where indentation is best left in the hands of the author, instead of following a strict "style guide."

      If you want "strictly styled indentation," run the code through a processor and see it in "alle ist in ordnung" fashion - I find it hard to believe that the author has nothing to offer beyond pedantically following the rules.

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

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

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

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

    19. Re:"The code comes out cleaner"? by phantomfive · · Score: 0

      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

      Yeah that's well said.

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

      You forgot one point:
      3) Make the code efficient.

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

    22. Re:"The code comes out cleaner"? by pla · · Score: 1

      I forced myself to limit code to 80 characters for a looong time.

      Then one day I realized I hadn't used a VT100 terminal to write code in well over a decade; and I hadn't used a PC with a CGI or MDI card in longer than that.

    23. Re:"The code comes out cleaner"? by jeremyp · · Score: 0

      No they don't. They make it look more readable but they do that by disguising the complexity (except maybe early return).

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    24. Re:"The code comes out cleaner"? by nblender · · Score: 1

      So long in fact that you forgot it was "MDA".

      I'll just take that geek card from you there....

    25. Re:"The code comes out cleaner"? by nblender · · Score: 1

      but please don't check in any changes after you've globally changed the indentation, you heathen.

    26. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      3 GOTO 1

    27. Re:"The code comes out cleaner"? by prunus.avium · · Score: 1

      I've been doing contract work on OpenStack for a bit and all I have to say is: FUCK PEP8!

    28. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      Define 'clean' in terms of code.

    29. Re:"The code comes out cleaner"? by phantomfive · · Score: 1

      You forgot one point:
      3) Make the code efficient.

      That's part of "making it work."
      Because not all code needs to be efficient, but if some code does need to be efficient, then you can't say it's complete if it's not.

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

      Dude, stop making fun of him.

      He clearly numbers everything in powers of 2, and is a true programmer.

    31. Re:"The code comes out cleaner"? by nitehawk214 · · Score: 1

      Well, I suppose I would consider the complete absence of code as clean, though.

      --
      I'm a good cook. I'm a fantastic eater. - Steven Brust
    32. Re:"The code comes out cleaner"? by FrozenGeek · · Score: 1

      This.

      I'm in the same boat - taking responsibility (I really don't want to claim ownership) of a ton of code that contains no comments, uses meaningless names, is poorly structured, and does things that some of our suppliers will not support. If your code is well-structured and uses meaningful names, you really don't need a lot of comments. I have encountered code in which the comments are wrong. IMO, incorrect comments are worse than no comments. When I see a comment, my initial reaction is to believe what it says. An incorrect comment sends me down a rabbit hold, wasting my time and leaving me frustrated and angry.

      --
      linquendum tondere
    33. Re:"The code comes out cleaner"? by 140Mandak262Jamuna · · Score: 1

      I would not consider non-working code as clean.

      I would not consider non-working gibberish as code.

      --
      sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
    34. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      or maybe your data doesn't belong in the code?

    35. Re:"The code comes out cleaner"? by Darinbob · · Score: 1

      Trump makes the code work, and makes it build its own wall too.

    36. Re:"The code comes out cleaner"? by Mr.+Slippery · · Score: 1

      Then one day I realized I hadn't used a VT100 terminal to write code in well over a decade

      80 columns goes back much longer than the VT100, it's a punch card thing.

      But longer lines needs a smaller font to fit on the screen, or take up real estate I could fill with another editor or terminal window. And I can just deal with 80 columns on my phone in landscape mode during an emergency SSH session into the server.

      A densely-printed book gets about 70 characters to a line. 80 is about the right number to have in your visual field.

      80 characters is the One True Line Length.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    37. Re:"The code comes out cleaner"? by bidule · · Score: 1

      You forgot one point:
      3) Make the code efficient.

      efficient = work + readable, I think that covers it

      --
      ID: the nose did not occur naturally, how would we wear glasses otherwise? (apologies to Voltaire)
    38. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      Jesus you are thick.

      Yes, legally no-one can stop me programming in whatever style I want.

      But a bunch of people who claim to represent a community will enforce that you do in order to become a member of that community or contribute back to it. So they have created a pressure to code in that style to the maximum extent that the power they have seized allows.

       

    39. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      If your system doesn't need a designated support rota, t's not important enough to bother with on off-time.

      If you're backpacking in the mountains, someone else should be on call.

      If it is an emergency and you're on support, get your ass to a computer.

    40. Re:"The code comes out cleaner"? by vrt3 · · Score: 1

      I get what you mean, but I think PEP8 is a bad example for your point. I think it's well thought out, places high value on readabilty, and doesn't advocate too strict application of its rules: it discusses when it can be appropriate to to break a guideline.

      In particular, your point about lining up colons in a dictionary definition doesn't stand. PEP8 doesn't want you to do that. See the last item in 'Pet Peeves'; PEP8 says

      Yes:

      x = 1
      y = 2
      long_variable = 3

      No:

      x = 1
      y = 2
      long_variable = 3

      --
      This sig under construction. Please check back later.
    41. Re:"The code comes out cleaner"? by vrt3 · · Score: 1

      Damn, that didn't get through correctly. Next attempt (or see the last item in https://www.python.org/dev/peps/pep-0008/#pet-peeves).

      Yes:

      x = 1
      y = 2
      long_variable = 3

      No:

      x             = 1
      y             = 2
      long_variable = 3

      --
      This sig under construction. Please check back later.
    42. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      > efficient = work + readable, I think that covers it

      Not quite. Efficient = minimizes unnecessary work.

    43. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      No worries, then you're just back in the second situation - "it's not clean and not working", so you can easily justify a re-write.

    44. Re:"The code comes out cleaner"? by __aaclcg7560 · · Score: 1

      But a bunch of people who claim to represent a community will enforce that you do in order to become a member of that community or contribute back to it.

      I guess you never lived in a condo, attended a church, or worked in a Fortune 500 company. Every community has representatives who will enforce what you do to become a member and contribute back. I like Python and I like PEP8, so I don't have a problem with the community.

    45. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      Sometimes that's part of step 1, and sometimes that's part of step 17. Depends on the problem.

    46. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      Hell - given the multiple language "issue" projects that I've worked on - code that works and I don't know why makes me ever so much more nervous than code that doesn't work and just immediately fails for whatever reason than I don't know.

      One is just broken - that's fine - I run in to broken code all the time on little used branches. Figure out what's intended if possible and fix.

      The other works. Sometimes. But you still don't know why. Obviously a larger issue unless it's the primary reason you're being called in on a case. Dear Great and Lesser Gods - syntax is my nemesis.

      Standards are great, it's just that there's so farking many (and versons of) to choose from!

      This is why comments matter. They should declare intent!

    47. Re:"The code comes out cleaner"? by WallyL · · Score: 1

      A true programmer would start at 0.

    48. Re:"The code comes out cleaner"? by pla · · Score: 1

      Ah, good catch. Mea culpa!

    49. Re:"The code comes out cleaner"? by Anonymous Coward · · Score: 0

      The "Fundamental Theorem of Readability" from The Art of Readable Code :

      "Code should be written to minimize the time it would take for someone else to understand it."

  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 Anonymous Coward · · Score: 0

      In that exercise, you still win $750.000 so, it would work fine.

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

    3. 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. Re:It's a tradeoff by Anonymous Coward · · Score: 0

      If you find yourself making such choices then you should probably just fold because you got there by chasing sunk costs and you're delusional if you think a capital injection will do anything but delay the inevitable. Absorbing liabilities to avoid insolvency doesn't make you solvent, it just keeps the corpse going for a little while longer.

      People who under-steer until it's too late to fix a problem are just as bad as people who over-steer at every minor hiccup.

    5. Re:It's a tradeoff by Anonymous Coward · · Score: 1

      Having run a small business I have to agree 100%.
      Bad code is bad, but bad code can be fixed or rewritten so long as the company is still afloat.
      Going broke is terminal. Good code, beautiful code, masterfully efficient code, cannot bring dead companies back to life.

    6. Re:It's a tradeoff by Anonymous Coward · · Score: 0

      I find that for maintenance and durability it is best to always code by intention - write your code how you intend it to work so it is absolutely clear to anyone capable of reading code exactly what you are intending to do (i.e don't do any fancy shit) - this also includes comments in the prefix to state the intention of the code - then comment by exception, unfortunately there are times where some work around is required, so the intention of the code is lost at this point comment clearly what the intention is and why it is not clear in the code.

    7. Re:It's a tradeoff by Anonymous Coward · · Score: 0

      What's that in English?

  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.
    2. Re:Bad Habits? by phantomfive · · Score: 1

      rely on IDEs...amirite?

      I consider any codebase that is tied to a particular IDE to be somewhat deficient......

      --
      "First they came for the slanderers and i said nothing."
    3. Re:Bad Habits? by LinuxIsGarbage · · Score: 1

      ...might consider upgrading to something exotic, like AutoIt, someday, but I've been saying that for four years now...

      I'm not a Programmer by trade. But for what I've done, it's almost exclusively been in AutoIT. It seems like an easy way to glue together applications. In addition to dozens of small home projects, I've even created applications for work which will audit open programs / files, their status, and SFTP them to a central server where the results from multiple computers are compiled.

      People might balk at the Basic like syntax, but it's much better than the atrocious AutoHotKey syntax. The included help file is really detailed, Scite environment good, and forum help / UDFs real useful.

    4. Re:Bad Habits? by Tablizer · · Score: 1

      I bet the contract required that every subroutine be commented, but said nothing of quality of comments.

      Some PHB probably noticed this AFTER the code was written and took advantage of the poor contract wording, telling somebody to write an automated commenter.

    5. Re:Bad Habits? by sconeu · · Score: 1

      I did that on a different project (thought it was for supporting documentation... see my other comment on this story)

      --
      General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
    6. Re:Bad Habits? by Tablizer · · Score: 1

      I see such for assembly being somewhat of a help because assembly op-codes are usually cryptic. But anybody qualified to alter the code should learn the op-codes anyhow.

      It does underscore the point though that the existence of comments/documentation and the usefulness of comments/documentation can be two very different things.

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

      Considering a continue to be a form of goto is stretching it I think. By that logic an if-else could be considered a form of goto.

      That said I have used goto statements for error handling before. It's about the only thing (in my experience) that a goto statement won't make things worse. There are probably other good use cases for it but not in my experience.

      Of course any kind of flow-control can be used badly. Someone posted an example here recently of bad code that used a whole bunch of if statements when a loop would have been much more concise and readable and just by virtue of it being much shorter less prone to bugs caused by human error while cutting/pasting.

    5. 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...
    6. Re:Copy and Paste. by JesseMcDonald · · Score: 1

      The continue and break targets are clear enough in very simply code. They're much less clear when placed inside several levels of nested blocks. A goto statement has a named target you can easily search for, while the target of a break or continue statement is merely the end of the enclosing loop (or in the case of break, a switch statement). This may or may not be the same as the end of the current block.

      Besides the lack of a named target, this points out another drawback of continue/break: wrapping code in a loop or switch statement can unintentionally change the branch target.

      I've seen code where the entire body of a large function was wrapped in a "do { ... } while (0)" loop just so that the programmer could use break in place of goto. It's not an improvement.

      Return statements always exit the enclosing function, so they're relatively easy to analyse. The risk with multiple return points is that you may want to add code which is run unconditionally before the function returns, and that means either restructuring the function or duplicating the cleanup code.

      Are there other ways? Sure. Any code using goto can be rewritten without it. A switch statement inside a loop can form a state machine with any control flow you want. But will that be clearer than using goto? Probably not.

      --
      "The state is that great fiction by which everyone tries to live at the expense of everyone else." - Bastiat
    7. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      Why are you adding functions without a context? Object oriented programming isn't new, but it's apparently still poorly understood. Make a Name, and call split on it if it's the same functionality. Then store one in a variable called person and another in a variable called company.

    8. 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.
    9. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      didn't read the text. but the subject is the one single cause that is causing most of the bugs.

    10. 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
    11. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      Likewise, will using a goto be clearer than the switch statement? Probably not, and the switch statement enforces a scope on the code in question (it must fall within the switch statement), where goto does not ensure this. The goto target could be embedded in an entirely different function.

      If your code is messed up enough that using goto makes it *clearer*, you've probably needed to refactor that code for a long, *long* time.

    12. Re:Copy and Paste. by jeremyp · · Score: 1

      continue, break, return, else and throw are all restricted forms of goto. while, do ... while and for loops are codifications of "safe" patterns of if and goto.

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

      Likewise, will using a goto be clearer than the switch statement? Probably not, and the switch statement enforces a scope on the code in question (it must fall within the switch statement), where goto does not ensure this. The goto target could be embedded in an entirely different function.

      The goto will almost certainly be clearer. The concerns about branching between functions are misguided, as goto labels have function scope—you can't branch to a different function in standard C. Ergo, the effective scopes of a loop & switch statement enclosing the function and a goto statement are equivalent.

      The goto statement uses names, while the switch statement is using integers; if you want names you have to declare them separately, as an enum or with #define.

      You have to consider the possibility that the switch argument may not match any of the provided cases. With "goto", the compiler guarantees that the target label exists.

      The equivalent of "goto" is "var = NEW_STATE; continue;", which is less obvious than "goto label;" and is moreover affected by the scope issues I already addressed for the continue statement.

      Finally, are you sure that the code "must fall within the switch statement"? The branch source needn't be inside the switch, just inside the loop. The control variable could even be modified from outside the function—it's effectively a computed goto, which isn't otherwise available in standard C (though there is a GCC extension).

      --
      "The state is that great fiction by which everyone tries to live at the expense of everyone else." - Bastiat
    14. Re:Copy and Paste. by AmiMoJo · · Score: 1

      C has continue too. Where GOTO is really useful is for clean up code and error handling. In other languages you have try...catch...finally etc.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    15. 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 :)

    16. Re:Copy and Paste. by Espectr0 · · Score: 1

      you can't compare continue to goto. With goto you can jump to any line in the code. With continue you just go to the start of your current loop

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

    18. 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.
    19. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      This is my total pet peeve.

    20. Re:Copy and Paste. by jittles · · Score: 1

      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.

      So why don't you publicly expose the SplitPersonName function and the SplitCompanyName function and have those functions call a single function that is just called SplitString? Then you can have your readable code and only have to make changes to the split function in one place. It's like the best of both worlds. When I need a new parameter in a function, I keep the original function and just have it call the new function with a default value for the new parameter. Then I don't have to change anything anywhere, you just make sure your unit tests still work.

    21. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      There's no reason why "continue" must be anonymous, that's just how C works. Imagine a `continue next i` statement. Adding an inner `for j` loop would then be a safe operation.

    22. Re:Copy and Paste. by Junta · · Score: 1

      True, I generally put in an apologetic comment pointing out the duplication and why and how I tried to make it so that it won't get duplicated more than the one incident for this specific reason.

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

      I can't believe how many people continue to hold on to the concept that once unit testing is added to a project, suddenly the code is bulletproof and cannot be broken without detection. I'm doubly astonished when they hold on to that thought even in the face of bugs cropping up when put to use.

      That's not to say the strategy is totally without merit, but it should be considered a mitigation of risk rather than a removal of risk.

      --
      XML is like violence. If it doesn't solve the problem, use more.
    24. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      You don't need to have comprehensive tests, you just need to test edge and corner cases. Of course if you can't identify these most of the time, you probably shouldn't be programming. I have complex interacting system that were designed from the start to handle nearly every failure case. Once or twice in the lifetime of a project, might there be a failure that can't be immediately figure out in a few minutes just by hearing the description, but nearly every possible handlable failure is accounted for.

      My longest bug fix for a production system took me an hour to figure out a multi-threaded race condition, but I didn't even have to use the debugger. I just white-boarded the components and implementations and based on the characteristics of the phenomena, limited it to a certain piece of code. Wrote a lock-free threadsafe algorithm. Fixed. I never even ran it through the debugger. I just changed the code, recompiled, and the issue was fixed.

    25. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      Goto in C can't leave the function. I think people are railing against the BASIC etc goto that indeed could go anywhere.

    26. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      the do { ... } while(0); trick is useful for when you want to do a load of initialization but handle the failure case of one of the parts and cleanup before returning. I prefer RAII but sometimes you can't make it fit neatly, it's like anything in coding, you gotta use it the best method you can think of for the job, not rigidly stick to one thing.

    27. Re:Copy and Paste. by Anonymous Coward · · Score: 0

      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.

      i made each class have a static string called 'tag', and the value is the clasname.
      when i output to console i include the tag at the front, so every printout on the console has the class name. its nifty.

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

      The boss or the developer? Requiring documentation that will inevitably go stale is a useless policy. A better practice is to require small, simple, and clear functions that anyone who is an expert in the field will understand. Documentation will inevitably diverge from the actual executing code.

    2. Re:Documentation by Anonymous Coward · · Score: 0

      Programmer's performance evaluations should consist largely of how well other programmers can maintain their code. On evaluation day you just assign a few programmers to go into the subject's code and change something. The time it takes them is the programmer's evaluation score.

    3. Re:Documentation by Anonymous Coward · · Score: 1

      If the unit of work provided by a function changes, then a programmer who understands what maintenance is like will also update the comment describing what it does.

      My goodness, people! How hard is it to declare what something does? Get off my lawn!

    4. Re:Documentation by Gr8Apes · · Score: 1

      So longer is better (higher score)?

      --
      The cesspool just got a check and balance.
    5. 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
    6. Re:Documentation by khasim · · Score: 0

      Agreed. It's okay to "break" his other "rules" AS LONG AS YOU CORRECTLY DOCUMENT WHAT AND WHY.

      Fucking up the documentation just to show that you're smarter than your boss is childish.

    7. Re:Documentation by Tablizer · · Score: 1

      So, how does shooting make you feel?

    8. Re:Documentation by __aaclcg7560 · · Score: 1

      I have yet to see a programmer who can do two headshots with a single bullet.

    9. Re:Documentation by Anonymous Coward · · Score: 1, Interesting

      That's nice in theory but in a lot of cases the code consists of many revisions done by many different developers over a number of years.

      If there is a piece of code that can be credited (at least in large part) to just one person it's probably fairly young code.

      In about 25 years I've only worked one place where I truly could take responsibility for EVERYTHING in the code as I had written 95% of it and the 5% I hadn't had been around long enough that if I had a problem with it I should have changed that too. But who would have reviewed my code when I was the only developer?

      Perhaps something as simple as analyzing who fucked up the code is good. I've often checked to see who fucked up the code when I find a bug and to see what else might have gotten fucked up along with it - sometimes I found out it was me that fucked it up.

      Everybody makes mistakes but sometimes looking at a diff between 2 revisions can reveal a programmer who either didn't understand what he was doing or just didn't fucking care.

    10. Re:Documentation by Anonymous Coward · · Score: 0

      Why do you say, "He should have been shot."?

    11. Re:Documentation by Anonymous Coward · · Score: 1

      Programmer's performance evaluations should consist largely of how well other programmers can maintain their code.

      No, it should not. Programmers do not exist to make other programmers' lives easier. Programmers solve problems. "Does the code do what we need it to do?" is the primary metric. If you need the code to be instructive, then that's what it needs to be. If you need the code to perform under strict realtime constraints, then that's what it needs to do. If you need the code to be usable by many other programmers in many other programmers, then it needs to have a clean interface, adhere to standards, etc.. But very rarely is changing code that you do not fully understand a good idea, and the ease with which some other programmer can make ad-hoc changes is at best irrelevant, but more likely a dangerously misleading metric.

    12. Re:Documentation by Anonymous Coward · · Score: 0

      Occam programmers. (Not many around though.)

    13. Re:Documentation by Anonymous Coward · · Score: 0

      I've done it... in a video game. Team Fortress 2 has an achievement for it. It requires a non-default sniper rifle.

      Perhaps you meant to say you have yet to meet programmer who can outsmart boo-let.

    14. Re: Documentation by Anonymous Coward · · Score: 0

      Does the Quake3 raingun ammo count as a bullet? If so, you should retro game more.

    15. Re:Documentation by Anonymous Coward · · Score: 0

      I've done it in TF2, and possibly CoD4. If they line up just right, it's possible. Never IRL though.

    16. Re:Documentation by sconeu · · Score: 1

      I was once loaned to a project... About 50K lines of UYK-20 assembly code.

      Somebody had specified the pseudo-code (PDL) as a deliverable. They had a team of 5 guys reverse engineering the assembly and trying to write PDL.

      I got brought in to automate the process if possible. We wound up generating a ton of PDL that read something like:

      SET THE CONTENTS OF REGISTER 2 TO THE CONTENTS OF REGISTER 1

      and so forth. On the other hand, all block comments, etc... in the source were preserved. It wound up generating a 3 foot tall stack of fan-fold, but the Army was happy.

      --
      General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
    17. Re:Documentation by Anonymous Coward · · Score: 0

      What about the situation where a problem domain is too hard for nearly everyone at the company except a small handful of people? You can't understand the code without understanding the problem it solves.

    18. Re:Documentation by Anonymous Coward · · Score: 0

      Make it a policy to read the documentation when you update the code. If your update causes the documentation to be outdated, it's your responsibility to update the corresponding documentation.

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

      Ever worked at a place where EVERY LINE has to be documented? I had a manager who didn't know any programming but wanted directors to think he did, so every line was commented and he could explain in detail just by paraphrasing the comments.

    21. Re:Documentation by Anonymous Coward · · Score: 0

      It's really a question of timing and caliber.

    22. Re:Documentation by prunus.avium · · Score: 1

      Define "small". I have worked on one particular code base where each function was 10 lines or less which was an absolute horror to work on because it created a mess to drill down through 15 layers of function calls to find out what went wrong. If the code can't be used/called from anywhere else, it doesn't need to be in its own function!

    23. Re:Documentation by ItsJustAPseudonym · · Score: 1

      He should have been shot.

      Don't you ever say Hello? -- Eliza

    24. Re:Documentation by Anonymous Coward · · Score: 0

      You must be a manager you talk just like my old boss.

    25. Re:Documentation by Anonymous Coward · · Score: 0

      I have yet to see a programmer who can do two headshots with a single bullet.

      see -- maybe that's something Extreme Programming pair coding would help with.

    26. Re:Documentation by Anonymous Coward · · Score: 0

      He just has the same interface.

    27. Re:Documentation by Dog-Cow · · Score: 1

      Yuck. Large functions are harder to read. If it's long, it's hard to tell how many parts will be hit for a particular code path. Understanding everything the code does is harder. It's a real pain to trace through in the debugger. A short function calling a set of single-caller functions is trivial to debug with a combination of step-over and step-into.

    28. Re:Documentation by MadKeithV · · Score: 1

      You can re-use an OO bullet!

    29. Re:Documentation by prunus.avium · · Score: 1

      Ah, right. Debuggers. I rarely use them. And when I do it's usually for tracing through a memory dump from a crash.

      In the real-time, embedded space there are way too many instances where you can't pause the execution. As an example, I need to debug a network communication issue but I don't control the server side of the network. The only option I have is debug messages and offline stack traces.

    30. Re: Documentation by Anonymous Coward · · Score: 0

      I've done it in battlefield3 and 4. Multiple times. One time in a CQC match my friend got a triple headshot, 3 enemies running down the hall all in a line. Hilarious.

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

      a call stack 20 layers deep.

      This here is my pet peeve of most 'modern' code projects, an insane call stack. Sometimes there's good reason, but often it's simply because the project is badly duct taped together rather than carefully thought out.

      Exacerbated in a lot of cases even more by having multiple over the network calls to chain several of these sorts of atrocities together. I have seen a team charged with being a sort of single middleware for a pretty straightforward sort of job self-create 4 distinct processes that each get involved in every transaction, traversing not only multiple server side languages (python, perl, groovy, and java), and multiple frameworks of each language (django, another home grown python thing, spring), each layer imposing their own HTTP based api, and two of them having their own SQL datastore and a third also having a distinct datastore, just not SQL.

      --
      XML is like violence. If it doesn't solve the problem, use more.
    2. Re:long methods and coupling by tlambert · · Score: 1

      long methods - someone thought it a good idea to limit every method to no more than 20 lines.

      Show them tcp_input(). After they have a heart attack at the number of pages it takes to implement the input state machine for the TCP protocol, bury them, and get on with your life.

    3. Re:long methods and coupling by Anonymous Coward · · Score: 0

      Our call stacks are currently getting insane because of a particular section of code. We have an abstract base class. It has a few sub-types, so we visit it. Each sub-type has between two and four sub-types, which we visit. Most of those have two or three sub-types, which we visit, and one has 80 of the fucking things. Which we visit. EACH of those 80 sub-types will involve a visit across between 5 and 20 totally different derived classes to disentangle what they are.

      Logically, the structure actually genuinely makes sense. I was involved in setting it up, and I agreed (and agree) with the setup of it. On the other hand, it's been down primarily to me to implement the entire edifice. The resulting production code is going to be pretty clean and each class will look pretty sane, and also each visitor is unit tested, but debugging the integrated thing is a joyless task of stepping through visitor patterns, and call stacks with nested visitor upon nested visitor. I think today I managed to get down to ten or twelve nested visitors thanks to additional work I had to do for some of the types.

    4. Re:long methods and coupling by Dastardly · · Score: 1

      When I have run into long methods the solution usually is not a deep call stack, but instead that the method has chained together 20 10 line logical units. It would make the code more readable to have that be 20 sequential (not nested) calls to well named functions that accurately describe what they are doing. Often those logical units are different if/else blocks as well, so extracting them makes it easier to unit test all branches rather than trying to set up 200 different branch possibilities on one method.

    5. 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!"
    6. Re:long methods and coupling by plover · · Score: 1

      Regarding the hard problem of naming things, and the 'long names' problem, I aim for a two-word name that expresses the intent of the method. 'PrintInvoice' or 'CalculateSalesTax' are pretty clearly stating what they do. If the best name includes the word 'and', such as 'CalculateTaxAndPrintInvoice', it's a flag that the method or class may have too much responsibility, and the method probably lacks cohesion.

      --
      John
    7. Re:long methods and coupling by Anonymous Coward · · Score: 0

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

      Yeah but can you run tests on that?

    8. Re:long methods and coupling by wienerschnizzel · · Score: 1

      My rule of thumb for long methods is very simple:

      Is there a routine that can be reused in other parts of your code?
      Are there complex/critical parts that should be (unit) tested separately?

      If the answer to any of those questions is yes, split the method. In my experience, most of the time when I see a very long method, it fails the second question - testability. I can't really remember an example of a very long method that would just contain simple straightforward stuff.

  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 Anonymous Coward · · Score: 0

      Yep: in other words, Lies To Children.

    3. Re:GOTOs in C by Anonymous Coward · · Score: 0

      I prefer the COMEFROM statement or the computed COMEFROM for the ultimate thrill

    4. Re:GOTOs in C by JustNiz · · Score: 0

      Yuk on many levels.
      Try something like this:

      x=do_stuff();
      if ( x )
            x= do_more_stuff();
      if ( !x)
            {
            fix_my_mess();
            fix_it_4realz();
            }
      return x;

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

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

    8. Re:GOTOs in C by Anonymous Coward · · Score: 0

      I think a lot of gotophobia (yes, it is an irrational fear) stems from encountering BASIC in those important early years, where traditionally it is the primary means of branching and driven by line numbers -- which can lead to a mess. But C-style labelled gotos used judiciously do result in cleaner, more understandable code and the GP's is a canonical example: getting out cleanly in trouble. The alternative is ever-nested if()s or tedious, repeated if(ok)s. OK, you could jump out with a return but these can get overlooked or lead to repeated code, so I much prefer the goto/cleanup/single return approach.

    9. Re:GOTOs in C by UnderCoverPenguin · · Score: 1

      As JustNiz said, too much code and you're leaking internal logic.

      Try:

      int foo() {
              if (do_stuff() != 0) {
                      if (do_more_stuff() != 0) {
                              return SUCCESS;
                      }
              }
              clean_up_the_mess();
      }

      --
      Don't try to out wierd me, three-eyes. I get stranger things than you, free with my breakfast cereal. --Zaphod Beeblebr
    10. Re:GOTOs in C by Anonymous Coward · · Score: 0

      wtf? you seriously think your crap is better or more readable?

    11. Re:GOTOs in C by Anonymous Coward · · Score: 0

      Yuk again!
      1) Braces shall appear after ALL conditional statements, even for one-liners. The next guy to add a second line should not have to clean up after you and add the braces YOU should have added.
      2) Braces are not to be indented with their contents. They define the indent, they are not part of it.
      3) 1 space between operators and operands: x = do_stuff();

      How about just one if statement with less chance of branch misprediction?

      if (do_stuff() && do_more_stuff())
      {
      _ _ return SUCCESS;
      }
      fix_my_mess();
      fix_it_4realz();
      return ERROR;


      I do suppose you want each individual return code for debugging purposes, but just saying.

      P. S. How are you getting indentation in a comment? &nbsp is ignored.

    12. Re:GOTOs in C by Anonymous Coward · · Score: 1

      Because adding a function cleanup() automagically makes it more readable?

      As you may know, in real world that cleanup needs to clean up multiple local variables. So now what? You pass 10 local variables as arguments? You implement cleanup_1(), cleanup_2() ... cleanup_10() because at different error conditions it needs to clean up different variables? You nest them?

      I fail to see how it is better or more readable.

      There is only 1 right way to do it and it is goto.

    13. Re:GOTOs in C by Anonymous Coward · · Score: 0

      You're missing a return statement at the end for the error case. Compiler error.

    14. Re:GOTOs in C by Anonymous Coward · · Score: 0

      Ignoring whitespace and curly brace "dogma" for a moment, this version is cleaner than the original with no goto statements and no branch misprediction for expected outcomes:

      if (do_stuff() && do_more_stuff()) return SUCCESS;
      fix_my_mess();
      fix_it_4realz();
      return ERROR;

    15. Re:GOTOs in C by HornWumpus · · Score: 1

      Unless you've lived through it you won't understand just how awful FORTRAN calculated GOTOs are.

      Like a pointer, but the integer variable contains target line number. Which leads to entry points at every power of 2 line number and destination options per bit of the goto target line number int.

      --
      John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
    16. Re:GOTOs in C by angel'o'sphere · · Score: 1

      I guess you either made a to simple example or ... hm, sorry, that is easily written in an if ... else if structure.

      While the code is clear, I would put programmers writing that into a brain washing company. (My eyes don't want to skip X lines to find the label and then figure: you got cheated by an unnecessary goto which added no clarity at all ...)

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    17. Re:GOTOs in C by halivar · · Score: 1

      If you want to examine the return codes, you're quickly stuck in parentheses hell.
      If your chain has more than this trivial example, you're going to perform my favorite exercise, figuring out where in hell I'm going to put line breaks, indents, and closing paren's in my conditionals and still make it readable.

      In general, these are the sorts of shortcuts that are wonderful to write, but I end up unpacking anyways during debugging or maintenance..

    18. Re:GOTOs in C by Anonymous Coward · · Score: 0

      Some people hate goto so much that they're willing to make code even worse just to not use it.

    19. Re:GOTOs in C by Anonymous Coward · · Score: 0

      Goto is cruise control to spaghetti-land. Flag variables and structured programming will always have explicit accounting of how a codepath flows..

    20. Re:GOTOs in C by prunus.avium · · Score: 1

      It's a simplified case. Usually this type of thing comes in handy when allocating dynamic memory blocks. Developers from managed languages don't see the need but it comes in handy in C. Mix dynamic memory in with large switch() statements and the goto cleanup_and_return; style becomes easier to maintain.

      For example let's say we have a state machine implementation with 10 cases inside a switch and each one has to clean up some memory before returning.

      switch (state)
      {
      case 1:
          if (!do_something())
              free memory;
              return FAIL_1;
      case 2:
          if (!do_something_else())
              free memory;
              return FAIL_2;
      case 3: ...
      }

      It's easier to maintain the clean up at one location a la goto cleanup_and_return; than to make sure that each and every case cleans up the correct memory, especially if the clean up changes at some point.

      int return_value;
      switch (state)
      {
      case 1:
          if (!do_something())
              return_value = FAIL1;
              goto cleanup_and_return;
      case 2:
          if (!do_something_else())
              return_value = FAIL2;
              goto cleanup_and_return;
      case 3: ...
      }
      cleanup_and_return:
      free_memory;
      return return_value;

    21. Re:GOTOs in C by angel'o'sphere · · Score: 1

      Another bad example?

      Why not clean up in each switch and return from there?

      I don't get why you think the second code snipped is more clear or better maintainable then the first one.

      If you would work under me, you would be forced to follow the first code snipped as an example. Not by me, but by your coworkers ;D

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    22. Re:GOTOs in C by Darinbob · · Score: 1

      But then you have a boss who does not have the experience or expertise necessary to know that. The boss will think treat this guideline as an unbreakable taboo. Beware the boss who started in computer science merely as a stepping stone into management. Also beware the 24 year old boss who thinks he or she knows everything.

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

    24. Re:GOTOs in C by gnupun · · Score: 1

      But what if foo() allocates memory and/or other resources that must be freed on error? If fix_my_mess() and fix_it_4realz() is in another function, you need to make those resource variables *global*, which is very bad. This assumes fix_my_mess() etc. is inlined/macroed inside foo().

      I actually wrote code like that for a library, and goto was the best solution for cleanup.

    25. Re:GOTOs in C by goose-incarnated · · Score: 1

      This only works well for trivial examples - show us what the function looks like when it has 20 or checks to do, all of which need every function already executed to be cleaned up if the current one fails?

      --
      I'm a minority race. Save your vitriol for white people.
    26. Re:GOTOs in C by wienerschnizzel · · Score: 1

      But most importantly, no one can demonstrate how it is wrong.

      You may end up "cleaning up" something that's not there and crashing. While it's hard to see how that would be a problem in a simple function that you've written yourself, it becomes a problem with time - after it's grown to a couple hundred lines, modified by 10 people in the span of 6 years. The failure scenario might be relatively rare and not detected during testing.

    27. Re:GOTOs in C by Dog-Cow · · Score: 1

      If you find you're repeating code, especially in the same function, your structure is bad. If you refuse to allow good structure, you'd better hope you only employ idiots.

    28. Re:GOTOs in C by Anonymous Coward · · Score: 0

      Brackets on the same line. Fired.

    29. Re:GOTOs in C by angel'o'sphere · · Score: 1

      We both would repeat only one single line:
            you repeat the "goto somewhere"
      and I repeat: cleanup()

      Also I don't use C, I would use C++ and put clean-up code int the destructor of a local class/object.

      Bottom line if every case block in your switch has a goto, then YOU are likely one of those idiots you mention.

      Luckily I'm not employing People ;D I would likely never let one pass an interview :-/

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    30. Re:GOTOs in C by prunus.avium · · Score: 1

      Depending on the interviewer you might be okay. Asking questions means you have an open mind about a different way of doing things. For entry level positions, I've found that usually works out better.

      Calling a function to clean up allocated memory can lead to some really, really odd things like a pointer to a pointer to a pointer. Yes, I have seen that once and it made sense in that system. The main rule is if you allocate it, you clean it up. With C++ it's simpler to let the constructor-destructor deal with it which makes it nice but that's not an option with C.

      Also - and we're getting in to the embedded space with this one - why make a stack frame when a JMP will do? Unless you want to macro out the goto by making it look like a function (don't laugh, I've done this...for a reason) keeping things local is always "better".

      A function call - stack frame - generally has the following steps:
      1 - Push parameters on the stack (along with certain registers).
      2 - Push the return location on the stack
      3 - Branch to the new function
      4 - Push local variables on the stack (along with some other registers,maybe)

      And reverse (pop, return, pop, pop) those values on return.

      A goto is one function: JMP.

      I'm glossing over a few things like inline but you get the idea.

    31. Re:GOTOs in C by sjames · · Score: 1

      That works well as long as there isn't a lot of local state in the function. Of course, when you have some significant cleanup to do, there often is.

      The case for goto more commonly involves unwinding. For example, if you have to acquire multiple resources.

      Honestly, continue, break, and return are already just special cases of goto albeit they are often less ambiguous.

      Personally, when I find goto tempting, I take the "considered harmful" as a reminder. Would it unwind cleanly if I turn the logic inside out? Am I trying to do too much here? If not, goto may be the best answer.

    32. Re:GOTOs in C by sjames · · Score: 1

      Actually, in that case, I would set return_value before the switch, use break as usual, and then wrap free_memory with if(return_value).

      A better case is if you have taken several resources (mutex, spinlocks, etc) and you will discover the error condition inside a nested loop. Then you should definitely use goto to break out of the top level loop. You COULD add logic to each loop to fall out on return_value, but in the end that might be more confusing.

    33. Re:GOTOs in C by prunus.avium · · Score: 1

      Exactly. It's tricky to come up with a code snippet that's simple enough to be posted but still shows the messy parts.

      The switch I mentioned above could easily be inside a while loop with a blocking call to poll() which then has to loop through the file descriptors and...

      But try posting that code to /. :-)

  9. I'm a rebel. by Anonymous Coward · · Score: 0

    I know a lot of people think every method needs a goto, but I break that one when I can get away with it.

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

    1. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      "Spake".

    2. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      ... who knew more at the age of 10 that you will have learned by the day you die.

    3. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      "than"

    4. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      "learnt"

    5. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      Thus spoke the one who didn't like what he had been told, yet had no argument against it.

    6. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      Quoting Dante would be as apt. And about as dated.

    7. Re:Dijkstra Nailed It by Anonymous Coward · · Score: 0

      Why would you only want to do the things you know how to do?

    8. Re:Dijkstra Nailed It by Darinbob · · Score: 1

      Ain't no one got time to understand the code they have to write by Friday.

  11. 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 lorinc · · Score: 1

      Nice ones.

      There's also a Goldilocks size for functions: functions too long are a pain to decipher, and it's easy to get lost between calls when all functions are too short. The same applies for OOP with the trade off between one Godzilla class and the Lasagna of too many classes.

    2. Re:Lessons by Anonymous Coward · · Score: 1, Interesting

      My professor told me, keep your functions short enough to fit on one page. Longer than that, and you have to scroll to see it all, and you can't read it all at once and it gets confusing.

      I don't strictly adhere to this rule, but I do try to keep 99% of my functions to a page or less.

    3. Re:Lessons by Hussman32 · · Score: 1

      I can buy most of these, I would add that I like to include the type in the name when doing math (bln for boolean, i or int for integer etc.). I also make sure when it's declared that it's unit is defined in the declaration. I can't tell you how many times I've looked at 'temperature' and wondered if it's oC, oF, K or oR.

      --
      "Who are you?" "No one of consequence." "I must know." "Get used to disappointment."
    4. 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.

    5. 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(), ...

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

    7. Re:Lessons by Anonymous Coward · · Score: 0

      I'll see your Goldilocks and raise you a tcp_input().

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

      I meant real newspapers, not tabloids :-)

      (Do they still make those?)

      get_off_my_lawn(exclamation);

    9. Re:Lessons by Anonymous Coward · · Score: 0

      a monetary value (typically "double")

      If that wasn't sarcasm, you are hereby banned from working on programs which handle financial data.

    10. Re:Lessons by careysub · · Score: 1

      Good guidelines. Additionally, with the advent of smart editors with embedded refactoring, you should always rename functions, methods, and variables if they undergo semantic drift so that the names continue to reflect the concept/operation they represent.

      Knuth's concept of "literate programming" is not supported well by existing languages and programming environment in the form he conceived it - but it should be used as inspiration in writing code, so that the the naming and structure, with supporting comments (as needed), explains the design and operation of the code.

      --
      Starships were meant to fly, Hands up and touch the sky - Nicky Minaj
    11. Re:Lessons by careysub · · Score: 1

      What is this "page" you speak of?

      I have no trouble reading through multiple screens of code (that I didn't write). Now if too much logic is crammed into a single function/method, so that the function does not have a clear purpose, revealed by its name, or the code is poorly structured, then you do have a problem - but it is not because of the length per se. I do not want to see logic flow chopped up to fit arbitrary length limits. If I find myself reading bad code, it is not because of the length of the functions/methods.

      --
      Starships were meant to fly, Hands up and touch the sky - Nicky Minaj
    12. Re: Lessons by Anonymous Coward · · Score: 0

      I second that.

    13. Re:Lessons by Hussman32 · · Score: 1

      I know a lot of people don't like HN, 95% of the code I work on is engineering simulations and there was a time when mixed type expressions got you in trouble. I always used isFoo for boolean functions, and the blnFoo for loop flags.

      I was wondering if you meant a x.00 format as 'double' for monetary variables, or if you were planning the Superman 3/Office Space fractional penny hack.

      --
      "Who are you?" "No one of consequence." "I must know." "Get used to disappointment."
    14. Re:Lessons by Anonymous Coward · · Score: 0

      4: Strange... I'd rather see departmentOfHousingVendorID all over the code, rather than dhv_id. You know what the heck it is without referring to a comment 8 screens of code from the point of use you're interested in, and unless you hunt and peck, it doesn't really take all that long to type.

      The number of times I've seen code that organically 'grew' namespace collisions has taught me that fully specifying namespaces will, in the long run, *save* you time. In one case, it happened *literally* 3 days after being told, in no uncertain terms, to stop fully declaring namespaces, because it was too verbose. The code I had written was pretty much the *only* thing that didn't get broken by the refactoring that caused the collision. I went back to fully declaring namespaces at that point, and the subject was quietly dropped. The developer who caused the collision spent the next week fixing it.

    15. Re:Lessons by Tablizer · · Score: 1

      Many languages don't offer money-friendly types. If one is careful about rounding at the right time, one can live with Double for smaller amounts.

    16. Re:Lessons by Tablizer · · Score: 1

      One is weighing the cost of slower code reading against naming collision risk here. The slower reading is a constant but small "tax", while the name collision is a relatively rare but notable event when it does occur. I'm not convinced the average longer run cost of name collisions is greater than the average longer run reading "tax".

      Perhaps a compromise is order: dh_vndr_id or dhous_vndr_id.

      Maybe your shop's language or coding style increases the risk of name collisions more than average. If you have a large code base, you probably want context, name-space, and/or class qualifiers anyhow.

    17. Re:Lessons by Darinbob · · Score: 1

      Variable names should be like pronouns. The whole point of a pronoun is to have a short and understandable shortcut for a longer concept. "It", "he", "she", "them". That's why spelling out the entire thing, DeptOfHousingVendorID, is nonsensical. No one would talk in a natural language that way, "I went down to the department of housing to talk to the department of housing vendor, and while I was at the department of housing I noticed that the department of housing vendor's ID had fallen off into the floor, so I picked up the department of housing vendor's ID from off the department of housing floor and handed the department of housing vendor's ID to the department of housing vendor, who said thanks."

      Even Loglan, the inscrutably precise artificial language, uses inscrutably precise pronouns. Otherwise the confusing language would be both confusing and verbose.

    18. Re:Lessons by Darinbob · · Score: 1

      See, no one knows what headlines are anymore, they're being confused with clickbait.
      Maybe a better analogy for newer programmers is to treat documentation like Tweets.

    19. Re:Lessons by mjwx · · Score: 1

      I meant real newspapers, not tabloids :-)

      The closest thing we have to a real newspaper these days are organisations like the BBC and AFAIK the Beeb has never been in print.

      --
      Calling someone a "hater" only means you can not rationally rebut their argument.
    20. Re:Lessons by flargleblarg · · Score: 1

      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.

      Yup. Hear hear! This is a sign that you are a good, seasoned programmer.

      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.

      Excellent!

      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.

      Perfect. As it should be! Nice work.

    21. Re:Lessons by flargleblarg · · Score: 1

      Perhaps a compromise is order: dh_vndr_id or dhous_vndr_id.

      What in God's name is that variable for? You actually know of production code that abbreviates "vendor" as "vndr" and "house" as "hous"? Excuse me while I go vomit...

      Seriously, what's wrong with dhouse_vendor_id?

    22. Re:Lessons by Anonymous Coward · · Score: 0

      Regarding [1], I have followed Slashdot's summary as the guideline for variable naming and commenting, all my life. My coworkers tell me my code is crap because it is full of typos, spelling errors and misleading to what the code actually does, but I don't give a siht to those suckers.

    23. Re:Lessons by plover · · Score: 1

      The problem your professor was cautioning you about was that of complexity. Another way to approach it is to do a quick cyclomatic complexity count in your head. If the code needs an exponentially growing number of tests to exercise all possible code paths, use an Extract Method to subdivide out some of the nested if statements or nested loops, and name the new method based on the intent of the newly encapsulated logic. You'll find the functions become better-sized regardless of how many screen pages they may occupy.

      --
      John
    24. Re:Lessons by plover · · Score: 1

      Variable names should be like pronouns. The whole point of a pronoun is to have a short and understandable shortcut for a longer concept. "It", "he", "she", "them". That's why spelling out the entire thing, DeptOfHousingVendorID, is nonsensical. No one would talk in a natural language that way, "I went down to the department of housing to talk to the department of housing vendor, and while I was at the department of housing I noticed that the department of housing vendor's ID had fallen off into the floor, so I picked up the department of housing vendor's ID from off the department of housing floor and handed the department of housing vendor's ID to the department of housing vendor, who said thanks."

      It's also a warning. Is this the only data associated with the Department of Housing, or are there other attributes that belong together? Maybe the right answer is DepartmentOfHousing.VendorID that complements the DepartmentOfHousing.VendorName.

      --
      John
    25. Re: Lessons by Anonymous Coward · · Score: 0

      The long version i great as a parameter so your callef sknow what it means. But it is too long to use on every line of the code. And it is ok to use abbreviations internally, as internally we know what they mean.

    26. Re:Lessons by Anonymous Coward · · Score: 0

      I ascribe the the idea that a function should do something. Not half of something and not two and a half of something. But a whole something. If your approach is sane usually your functions will be about a page. And if they aren't then so be it.

    27. Re:Lessons by Anonymous Coward · · Score: 0

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

      If you follow the format of modern day's online news headlines then the code comments for function would look like this:
      /*
      If you run this function, you won't believe what happens next!
      */

    28. Re:Lessons by gsslay · · Score: 1

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

      The problem I have with "self-documenting" code is that you can only ever tell from it what the code is doing. It doesn't tell you why, that can only be a best guess. Only decent documentation can tell for sure.

      So, to give an ultra simple example, if I have a line of code that says

      index += 1;

      Yes, it's obvious the index is getting incremented. But why this should be happening may be completely unfathomable, and indeed may appear to subsequent coders to be a bug. Only documented code can explain all.

    29. Re:Lessons by squiggleslash · · Score: 1

      I tend to be concerned people won't read my code, and thus will ignore potentially dangerous bugs I may have slipped in by accident. That's why I _always_ give my function names clickbait headlines.

      Sample:

      trick you_wont_believe_what_this_does(int x) {
      trick simple_trick = this_function_will_change_the_way_you_look_at_its_argument(x);
      if(simple_trick == null) {
      simple_trick = warren_buffet_invested_in_this_argument_nobody_has_head_of(x);
      }

      return { simple_trick.data, 0, FIVE_WAYS_ANDROID_IS_BETTER_THAN_IOS };
      }

      Initially it's a little harder to understand, but as programmers find they read it anyway, it ends up with them having a better core understanding of the entire system.

      --
      You are not alone. This is not normal. None of this is normal.
    30. Re:Lessons by billybob2001 · · Score: 1

      If one is careful about rounding at the right time, one can live with Double for smaller amounts.

      It's fine for a small amount, e.g. zero.

      The next smallest amount 0.01 can not be held exactly in a Double. Nor can 0.1

      DO NOT USE DOUBLE FOR MONEY.

      (or for any figures which need to be stored exactly)

      Multiply everything up by the required factors of 10 and store the value as an integer, e.g. a number of cents.

      Or write your own decimal class, maybe with an integer to hold the dollars and another for the cents (and another for the tenths or hundredths if you need them).

    31. Re:Lessons by Anonymous Coward · · Score: 0

      I try to keep my functions short enough that I can always see the declaration of a variable at the top.

      That way I never find myself wondering what the type of a variable is.

      HN isn't meant to include the data type anyway; it should provide meaningful semantics that tell you how the variable is used, not what it is.

    32. Re:Lessons by Tablizer · · Score: 1

      As I mentioned nearby, many languages don't support any money-friendly types.

      Using integers or self-rolled "number string" libraries carry their own risks, both machine and human.

      I've used Double before many times for money without problems. The trick is to round the values to 2 decimals before and after every multiplication or division, and before saving.

      Or to keep it simple: "round all values before and after any math".

      One can make four wrapper functions: add_dollar(), subtract_dollar(), multiply_dollar(), and divide_dollar(). Example:

      function multiply_dollar(d1, d2) {
        places = 2;
        r1 = round(d1, places);
        r2 = round(d2, places);
        result = r1 * r2;
        result = round(result, places);
        return(result);
      }

    33. Re:Lessons by Tablizer · · Score: 1

      If Microsoft were honest, that's what their comments would look like.

  12. Zen by KatchooNJ · · Score: 1

    Bingo... the first rule is to be as zen as possible with your programming. Clean and efficient... no bullshit.

    --
    "Never give up, for that is just the time and place when the tide will change." -Harriet Beecher Stowe ^_^
  13. 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.

    1. Re:One extra space per bracket by Anonymous Coward · · Score: 0

      Oh YOU'RE the ass hat we've been looking to shiv out behind the dumpster.

    2. Re:One extra space per bracket by Anonymous Coward · · Score: 0

      Finally, I've found you!

  14. My name is Jim. I like short variable names by GoodNewsJimDotCom · · Score: 0

    Mainline thoughts are that long variable names are better since you can remember what they do. I like short variable names if they're just used for a short time and not continually used throught the global scope. Short variable names have the following strengths: quicker to type so code is written faster, doesn't make you do mental work of focusing on the variable name very long so you can stay focused on the code, and job security since your code can't be read by anyone besides yourself. That last part is mostly a joke.

    1. Re:My name is Jim. I like short variable names by just_a_monkey · · Score: 1

      Short variable names have the following strengths: quicker to type so code is written faster,

      You maybe should look into getting an IDE with Intellisense.

      --
      How inappropriate to call this planet Earth, when clearly it is Ocean.
    2. Re:My name is Jim. I like short variable names by Actually,+I+do+RTFA · · Score: 1

      Low lifespan variables should have short names. Those short names should repeat. For instance, every time you iterate through an array (single depth) I see no reason not to use the same iterator name.

      --
      Your ad here. Ask me how!
    3. Re:My name is Jim. I like short variable names by Anonymous Coward · · Score: 0

      If a variable is short-lived, and has a small scope of use, you can get get away with shorter names.
      If a variable hangs around for a while, gets passed around a lot (by reference *or* value), you probably want to give it a descriptive name.
      public void UpdateVendors()
      { // You want to give this a meaningful name, because it gets used more
          Namespace.Collections.VendorList foodVendors = GetVendors(...); // a variable named 'i' here is fine, because its scope is small enough that there's little question about its purpose // If this were a larger block of code, you might want to call 'i' something like 'vendorIndex' instead.
          for(System.Int32 i=0;ivendors.Count;i++)
          {
              RefreshVendorCatalog(foodVendors[i]);
          } //Do other stuff with foodVendors ... ...
          foodVendors.Save();
      }
      private void RefreshVendorCatalog(Namespace.Vendor vendor)
      { // lots and lots of code here, with vendor and/or its properties used, manipulated, and passed to other methods as a parameter.
      }

    4. Re:My name is Jim. I like short variable names by prunus.avium · · Score: 1

      I once worked with a programmer named Vincent. Every variable was v followed by a number.

      int v1;
      char *v2;
      struct wtf_is_this_thing v3;
      struct wtf_is_this_thing *v4;

      I had a severe dislike for Vincent.

    5. Re: My name is Jim. I like short variable names by GoodNewsJimDotCom · · Score: 1

      Exactly. Stuff used throught the project is better given a longer name.

  15. Programming habit No. 1: Using goto by Anonymous Coward · · Score: 0

    Fuck you, article writer.

  16. Not really about "better, more efficient" code by UnknowingFool · · Score: 1

    Many of the rules in the article are about making the code easier to understand for yourself or whoever takes over when you have to leave a job or role. For example, you could put every single commands into one line; heck the entire program could be one really long line. I would argue it would be more efficient on disk space, but if you had to debug or modify it, it would be a mess. I don't code much but when I have to look over what I've done a year or two later, it's easier on me if I followed those rules.

    --
    Well, there's spam egg sausage and spam, that's not got much spam in it.
  17. ComeFrom's by QuietLagoon · · Score: 1

    I love to use the ComeFrom statement. It just makes the logic of the program so much easier to follow when others need to apply that very rare patch to my code.

  18. Breaking out of the middle of a loop by Sowelu · · Score: 1

    Since when is returning from the middle of a loop a bad thing? I've never been taught that, and it certainly hasn't been a guiding principle in any code base I've worked in.

    1. Re:Breaking out of the middle of a loop by avandesande · · Score: 1

      I think it's an extension of best practice having only one return in a function... which I kind of agree with since it works into your try catch loop. If you need more than one you probably need to split break up your method into more than one function

      --
      love is just extroverted narcissism
    2. 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...
    3. Re:Breaking out of the middle of a loop by Yunzil · · Score: 1

      There are a lot of people out there who subscribe to the "single point of exit" theory, meaning all your code paths through a function should lead to the same return point.

      I am not one of those people.

    4. Re:Breaking out of the middle of a loop by AK+Marc · · Score: 0

      It's a form of GOTO, and all that implies.

    5. Re:Breaking out of the middle of a loop by angel'o'sphere · · Score: 1

      Sorry, but if I see one converting this:

      if (xy)
            return 1
      else
            return 0

      into code with one return, I personally chain him onto the wall in the basement, and let him rot in his own shit.

      If you can not follow simple program logic with multiple returns, chance is: the damn function is to big, not that there are to many returns.

      If believe otherwise, pick a different profession!

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    6. Re:Breaking out of the middle of a loop by angel'o'sphere · · Score: 0

      Sorry, but if I see one converting this:

      if (x < y)
            return -1
      else if (x > y)
            return 1
      else
            return 0

      into code with one return, I personally chain him onto the wall in the basement, and let him rot in his own shit.

      If you can not follow simple program logic with multiple returns, chance is: the damn function is to big, not that there are to many returns.

      If believe otherwise, pick a different profession!

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    7. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      Break is an ugly hack to avoid GOTO.

    8. Re:Breaking out of the middle of a loop by Fwipp · · Score: 1

      Drop the elses.
      if (x < y):
              return -1
      if (x > y):
              return 1
      return 0

    9. Re:Breaking out of the middle of a loop by sl149q · · Score: 1

      Function calls are a form of GOTO.

      Loops are a form of GOTO.

      Conditionals are a form of GOTO.

    10. Re:Breaking out of the middle of a loop by angel'o'sphere · · Score: 1

      Compiles to the same code ;D

      But yes, you are right ... looks even more clearer then.

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    11. Re:Breaking out of the middle of a loop by prunus.avium · · Score: 1

      If could be a return in the middle of a conditional inside a loop...No GOTO there!

    12. Re:Breaking out of the middle of a loop by AK+Marc · · Score: 1

      How is that different than a single return at the end, and a GOTO in the loop that points to the return? GOTO return. It's a form of GOTO.

    13. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      return (xy?1:0);

    14. Re:Breaking out of the middle of a loop by Fwipp · · Score: 1

      Yeah sorry; I shoulda been more clear that it was just a style thing I prefer. I'm a big fan of early-return, especially for error-handling cases.

    15. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      return (xy?1:0);

      What's wrong with you guys? Less time spent typing and reading leaves more time for thinking.

    16. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      Sorry, but if I see one converting this:

      if (xy)

            return 1
      else

            return 0

      into code with one return, I personally chain him onto the wall in the basement, and let him rot in his own shit.

      If you can not follow simple program logic with multiple returns, chance is: the damn function is to big, not that there are to many returns.

      If believe otherwise, pick a different profession!

      return xy? 1 : 0;

    17. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      Sorry, but if I see one converting this:

      if (x < y)

            return -1
      else if (x > y)

            return 1
      else

            return 0

      into code with one return, I personally chain him onto the wall in the basement, and let him rot in his own shit.

      If you can not follow simple program logic with multiple returns, chance is: the damn function is to big, not that there are to many returns.

      If believe otherwise, pick a different profession!

      return ((x y)? 1 : 0);

    18. Re:Breaking out of the middle of a loop by CrashNBrn · · Score: 1

      Drop it all:
      return (x < y)?-1:(x > y)?1:0

    19. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      And damn Slashdot for eating the <y?:-1:x>

    20. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      You may consider them clean but I don't.
      Their use is analogous to the "friend" keyword in C++, in that the fact you are doing it at all shows there's a deeper problem with your logic/system design.
      I've been a professional software developer for 35 years and In all that time I've never seen an example of code that breaks out of a loop early that was justifiable for either efficiency or readability, and where I couldn't easily write a much cleaner version that didn't.

    21. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      ...and the real trouble with gotos/breaking out of loops early is that its not so easily scaleable or changeable, and there are often hidden edge cases.

    22. Re:Breaking out of the middle of a loop by goose-incarnated · · Score: 1

      You may consider them clean but I don't. Their use is analogous to the "friend" keyword in C++, in that the fact you are doing it at all shows there's a deeper problem with your logic/system design. I've been a professional software developer for 35 years and

      Whatever. I'm in 2 decades experience range myself.

      In all that time I've never seen an example of code that breaks out of a loop early that was justifiable for either efficiency or readability, and where I couldn't easily write a much cleaner version that didn't.

      Here, make this more readable two failure points in loop. Now trying making it more readable with 15 failure points within the loop.

      If you think that goto, continue, break and return cannot solve problems with readability then you haven't seen enough problems.

      --
      I'm a minority race. Save your vitriol for white people.
    23. Re:Breaking out of the middle of a loop by goose-incarnated · · Score: 1

      You may consider them clean but I don't. Their use is analogous to the "friend" keyword in C++, in that the fact you are doing it at all shows there's a deeper problem with your logic/system design. I've been a professional software developer for 35 years and

      Whatever. I'm in 2 decades experience range myself.

      In all that time I've never seen an example of code that breaks out of a loop early that was justifiable for either efficiency or readability, and where I couldn't easily write a much cleaner version that didn't.

      Here, make this more readable two failure points in loop.

      Sorry, in that link, the code I mean is in the function from line 86 onwards.

      --
      I'm a minority race. Save your vitriol for white people.
    24. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      That is a perfect example of what I said earlier about such things pointing to a deeper problem.
      In this case, its taht xstr_cat() is allocating memory then returning a pointer to it, so expecting/requiring the caller to know to clean up after, but only if the function worked.
      A much better approach is for xstr_cat to require the user to pass in memory for the function to fill.
      Apart from the classical arguments about not breaking encapsulation and avoiding situations with implied responsibility, it would also make the cleanup in the calling code less conditional, so would simplify that code too.

    25. Re:Breaking out of the middle of a loop by goose-incarnated · · Score: 1

      That is a perfect example of what I said earlier about such things pointing to a deeper problem. In this case, its taht xstr_cat() is allocating memory then returning a pointer to it, so expecting/requiring the caller to know to clean up after, but only if the function worked.

      It's actually a perfectly well-known idiom; look at the freebsd functions that do this. That you think it is a problem when the interface contract specifically mentions that it is the callers responsibility to free is indicative of a lack of experience with many unix systems on your part. It also means that you have never seen strdup() before.

      A much better approach is for xstr_cat to require the user to pass in memory for the function to fill.

      Regardless, we're talking about the idiom here - if it was not malloc(), it would be fopen() or similar. Either way, you have failed to provide a clean way to exit early while running all the cleanup handlers.

      Apart from the classical arguments about not breaking encapsulation and avoiding situations with implied responsibility, it would also make the cleanup in the calling code less conditional, so would simplify that code too.

      There is no implied responsibility - it's a function with a clearly defined and documented contract - the caller frees. You, personally, are unable to rewrite that particular function without goto's unless you greatly complicate the execution logic and repeat the cleanup statements. That's my point actually - most things are cleaner without goto, but handling exceptional conditions requires a jump out of the logic into specific error handling code. If you don't do the jump then you are going to sprinkle your cleanup code all over a function instead of having it all in one place.

      --
      I'm a minority race. Save your vitriol for white people.
    26. Re:Breaking out of the middle of a loop by Anonymous Coward · · Score: 0

      And bridges are a form of girder.

    27. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      I agree that its using an idiom dating from the early days of Unix that some functions (most notably in the STDC library, such as strdup) still use, but thats mostly because not so many people knew better back in the day when strdup was written, and no-one can change the interface to any standard C functions because it would break just about every existing application out there. Just because its used in functions in the C library and been around forever does not mean its a good idom to move forward on, or that we should keep doing it in new code.
      One example of some acknowledgement of how the STDC library is not some unquestionable authority on programming excellence is how functions like strcpy got (almost) fixed with the later addition of safer alternatives such as strncpy().
      The reality is that mallocing memory in a function then returning a pointer to it is undeniably FAR more prone to all sorts of problems (such as memory leaks) than having the caller provide the memory. It also goes against pretty much all modern software engineering principles and in my experience many company coding standards. Argument about whether some "BTW dont forget to free teh return value" comment in the header file is sufficient to somehow make everyone never forget to actually do it, or to ever make it an acceptably good idiom to use is subjective therefore pointless.
      What isn't subjective is that idom can also easily result in less flexible and efficient code. Example:
      Say I wanted the result of xstr_cat() to go into a memory structure I already had, such as a member of a struct. My way you can just directly provide a pointer to the element to xstr_cat.
      The existing way unavoidably causes a temporary copy to get malloced on the heap, which you'd then need to explicitly copy into the struct, and then remember to explicitly free the temporary copy you got back, or your app will have a memory leak.
      Any argument that the idiom used by xstr_cat() in your example results in a better approach than passing in a pointer to an existing buffer seems to be pretty much indefensible, regardless of how much code already does that.

    28. Re:Breaking out of the middle of a loop by goose-incarnated · · Score: 1

      I sorta figured you'd say that - I *have* seen this argument before, you know, and it still doesn't fly: moving around *where* allocation is done doesn't make the cleanup code go away. Even if we followed your software engineering principles the caller still faces the same problem.

      Let's look at an example of a caller-allocated memory function: IOW the caller preallocate memory for whatever foo/bar/baz needs. If any errors occur then you *still* need to have cleanup code. Here's an example with (as you insist) caller-allocated memory. Let's see how you rewrite this without gotos:

      int func (void) {
      // foo(), bar() and baz() needs buffers to fill, the caller allocates those buffers.
      char *one=NULL, *two=NULL, *three=NULL;
      if ((one = malloc (10))==NULL) goto errorexit;
      if ((two = malloc (10))==NULL) goto errorexit;
      if ((three = malloc (10))==NULL) goto errorexit;
      if (!foo (one)) goto errorexit; // foo() fills in buffer 'one'
      if (!bar (one, two)) goto errorexit; // bar() fills in buffer 'two', using contents of 'one'
      if (!baz (one, two, three)) goto errorexit; // baz() fills in buffer 'three', using contents of other buffers
      if (!correct (three)) goto errorexit;
      free (one);
      free (two);
      free (three);
      return 0;

      errorexit:
      free (one);
      free (two);
      free (three);
      return -1;
      }

      The problem remains whether or not you have a higher software engineering standard or not. You, personally, cannot make that code any clearer than it is right now. If you feel any use of malloc is wrong, then feel free to replace all occurrences of malloc() above with a file_open() type function. The problem of cleanup still remains.

      --
      I'm a minority race. Save your vitriol for white people.
    29. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      That makes no sense. Why are you mallocing at all? It would go on the stack. In which case that whole thing collapses to:
      int func (void)
        {
      char one[SOME_MAX], two[SOME_MAX], three[SOME_MAX];
      return (foo( one)) && (bar(one,two)) && (baz(one,two,three)) ? 0 : -1;
      }

    30. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      sorry, too many braces in last line. should look like this:

      return (foo( one) && bar(one,two) && baz(one,two,three)) ? 0 : -1;

    31. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      ...also another issue with functions that return pointers to memory they allocate themselves is that it can play havoc in multi threaded systems, especially if it is in a windows DLL.

    32. Re:Breaking out of the middle of a loop by goose-incarnated · · Score: 1

      You've ignored the question - how would you rewrite the given function, which does not return allocated memory, without using goto's? Consider it a challenge: you said it could be done after all :-)

      --
      I'm a minority race. Save your vitriol for white people.
    33. Re:Breaking out of the middle of a loop by JustNiz · · Score: 1

      Its a ridiculous example because there's no situation where you'd ever actually write code that looked like that in real life.
      You're basically showing me a collapsing wooden house built on shifting sand then asking me to show you a better engineered way to apply the duct tape that keeps it together than you used.
      That said, rather than ever use gotos I'd find the cleanest, simplest way to use conditionals that test previous results. whether I'd use a variable to hold status and then test it, or wheter I'd just test the return value directly would be a decision based on what keeps it most clear/simple.
      I can tell you from first-hand experience that whether you think its good or not, any code with any gotos in it at all wouldn't ever pass certification by the FAA so would never be allowed into an aircraft, for example.

  19. goto by hoffmanjon · · Score: 0

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

    1. Re:goto by CanEHdian · · Score: 1

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

      GOTO http://developers.slashdot.org/comments.pl?sid=8199619&cid=50767419

      --
      When the copyright term is "forever minus a day", live every day like it's the last.
    2. 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.

    3. Re:goto by Anonymous Coward · · Score: 0

      I have used goto quite a lot. Granted it was some inhouse language where goto was the only way to make a function call. You didn't say anything about which language.

      Using it in C was another story. I used it correctly at some point, but since I was developing/maintaining the code together with other people, I got flamed for it big time with arguments like "you can't avoid memory leaks if you use gotos" and some other incorrect statements. I ended up not using gotos, not due to technical reasons, but rather due to human reasons. I simply didn't bother to argue with mr. "I'm always right" about something I could avoid entirely with minor effort. I left the fights for more essential issues.

    4. Re:goto by prunus.avium · · Score: 1

      ...and if you don't understand assembly, you should probably not be coding...

      I'm willing to bet the number of programmers that understand assembly is far outnumbered by the ones that don't.

    5. Re:goto by Anonymous Coward · · Score: 0

      Easiest way to fix a lock leak: use RAII.

    6. Re:goto by Anonymous Coward · · Score: 0


      if ((you == BLUE) && (!know(line_to_goto))
          goto Fashion; /* why not? */

      Fashion:
            put_on(the_Ritz);

      while (1)
            dance();

  20. Better, more efficient? by Nchantim · · Score: 1

    From the article, there were 9 "Bad habits". Only one - "Programming habit No. 7: Breaking out of loops in the middle" could as see as ever making things more efficient. I also think that the article has Programming habit No. 1: Using goto and Programming habit No. 2: Eschewing documentation reversed in priority.
    Come to think of it.... goto isn't as bad as bubonic plague.

    1. Re:Better, more efficient? by Anonymous Coward · · Score: 0

      Come to think of it.... goto isn't as bad as bubonic plague.

      It isn't, but if you use them, then you will notice that your coworkers will stop talking to you and suddenly the svn server only provides read-only access. When asking the server admin to fix the issue, he tells you to goto coding school first.
      Yeah, the biggest problem with goto is more of a religious crusade against it by people not fully understanding what it does. To be fair, it might be best not to use gotos if you don't understand them.

      As the habits to make the code more efficient. I joined a project written in ruby and was put through the guidelines there. Interestingly enough, the guidelines said to avoid comments if possible. Being interpertet at runtime, excessive comments would slow down execution time. This meant use self documenting code and if comments were needed, write them short and to the point. Naturally it would still be a sin not to add the needed comments to understand the code. That was actually an interesting experience and it forces you to rethink how you use comments. I think I ended up writing better comments in general from that experience. I still prefer compiled code where comments have no performance impact since that leaves room for adding 20 lines of comments if you want to add a table or whatever without considering performance.

      I'm not actually sure how much performance ruby (or any other "runtime compiled" language) loses due to comments. It might have been an overreaction, but considering the performance was already declared "too slow" and changing language wasn't an option, I do get the point. I assume less than what I got from optimizing the slow parts of the code. That too was interesting, but please never ask me again to optimize code without a profiler. Figuring out what code to work on is.... tricky to say the least.

  21. Unapologetically guilty. by pla · · Score: 1

    #3 (overly long lines) largely depends on the language you write in. SQL, for example, pretty much forces you to either write far-too-long lines, or to use tediously tall vertical layouts. The former lets you focus on the bigger-picture logic of a procedure, while the latter only matters if you care about quickly knowing the 10th field returned in a given selection.

    For #6 (reinventing data structures), gimme a frickin' break - I will not pull in a 3rd party library just to implement a data structure I can write in my sleep. Fortunately, most languages include just about every standard type imaginable in their standard libraries; but hell will get pretty frosty before I resort to an external dependency for something like a boring ol' red/black tree.

    #7, flat-out guilty as charged. Yes, when the code has nothing else to do, I'll return to the caller from just about anywhere. That said, I do typically try to organize my code such that I don't need to return from anywhere other than the end; but when that means ending up with half a dozen layers of nested ifs just to avoid returning early - Just do it.

    1. Re:Unapologetically guilty. by Anonymous Coward · · Score: 0

      re #6: Egotistic people like you are the reason why every open source project I've ever used on has had its own buggy version RB or 234 tree implementation. :(

      p.s. Do you also bang out test code in your sleep?

    2. Re:Unapologetically guilty. by ArcadioAlivioSincero · · Score: 1

      For #6 (reinventing data structures), gimme a frickin' break - I will not pull in a 3rd party library just to implement a data structure I can write in my sleep. Fortunately, most languages include just about every standard type imaginable in their standard libraries; but hell will get pretty frosty before I resort to an external dependency for something like a boring ol' red/black tree.

      Just curious, but are you saying here that if a language's standard library provides a data structure you need, you'd still implement it yourself or would you just use the one provided by the standard library? If the former, I personally wouldn't call using the one that comes with a language "3rd party". Also, in my experience, nobody really cares that you can implement data structure code from scratch every time except maybe other developers, and even in that case it's kind of iffy. They only care that you deliver a product on time, to spec, and relatively bug free. How you actually accomplish this is largely a don't-care.

    3. Re:Unapologetically guilty. by Anonymous Coward · · Score: 0

      You will only understand the wisdom of what he said when you grow up.

    4. Re:Unapologetically guilty. by pla · · Score: 1

      No, if the standard libraries include it, I wouldn't roll my own.

      And I didn't mean to say that I'd roll my own rather than use a 3rd party library just to show off - More a matter of maintainability. I find it very frustrating that so many open source projects have a dozen pointless external dependencies, all of which seem to break unless you can track down exactly the right version of FredsPrettyNumberFormattingLib v1.5.27b6, which conveniently doesn't exist anywhere except as the latest stable release. ;)

    5. Re:Unapologetically guilty. by Anonymous Coward · · Score: 0

      The OP already responded, but there can also be non-programming issues. Pulling in a whole 3rd-party library[1] for some minor structure or function can lead to potentially undesirable consequences with deployment, licensing, testing, and so on, which can outweigh the benefit of a trivial re-use. We have to consider these as well as programming issues such as code maintenance.

      - T

      [1] To be clear, I wouldn't consider the language's standard library, nor the base OS features/headers to be "3rd-party"

  22. cut and paste by hguorbray · · Score: 1

    sometimes it's easier to cut 'n paste than trying to paramaterize everything -especially early on when your banging out a quick report of proof of concept

    -although if/when I end up doing parameterization I have to hunt through the code and delete all the stuff that was obsoleted by the parameterization

    -I'm just sayin'

    1. Re:cut and paste by angel'o'sphere · · Score: 1

      Actually it is not.

      You select the code, and instead of hitting CTRL-C, you chose the 'refactoring': extract function/method.

      Done .... and where you wanted to paste it: you simply call it.

      Or what stone age language or stone age IDE do you use? Notepad?

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  23. I just do some Python by Anonymous Coward · · Score: 0

    And I have the bad habit of using the same variable names for everything, and something entirely unrelated to the variable. Works great - except for the day after.

    1. Re:I just do some Python by __aaclcg7560 · · Score: 1

      When I took Introduction to Java, a pair of students submitted the identical code except for one slight variation. One student used the x variable, the other student used the y variable. The class had a good laugh, the instructor had private conversations with the two students, and everyone submitted their own code.

    2. Re:I just do some Python by Anonymous Coward · · Score: 0

      When I took Introduction to Java, a pair of students submitted the identical code except for one slight variation. One student used the x variable, the other student used the y variable. The class had a good laugh, the instructor had private conversations with the two students, and everyone submitted their own code.

      I can beat that. When I was around 14 years old, I was in a class of 24 students and 8 handed in the very same English essay. To make this even better, no font or anything was changed and some people even failed to remove the name of the person they copied from, handing in printouts with multiple names on them. I thought it was funny until I realized it was something all the boys had done and I was one of the few "not part of the group". Not that I ever wanted to cheat and my own essay was better than the one they copied, but being isolated in class is no fun.

      To make matters worse, despite doing good in all written assignments and always making my homework, my English teacher ended up not recommending an academic path for me due to "no understanding of English or grammar". I had a fight to stay in school against such recommendation, but I did and not only did I become an engineer, I also speak two foreign languages quite well (English being one of them). Freakish power absuing teacher. He didn't give that recommendation to the boys he caught cheating.

    3. Re: I just do some Python by Anonymous Coward · · Score: 0

      How is not being part of a group of 8 out of 24 being isolated? Sorry mate you need to work on your self esteem. Be proud for your own work and love to be singled out as the one guy who can do it himself.

    4. Re:I just do some Python by Anonymous Coward · · Score: 0

      Depending on the assignment isn't there a good chance of people writing identical code if they've been in the same class?

    5. Re:I just do some Python by __aaclcg7560 · · Score: 1

      The two source files had identical file sizes and were compared against each other byte-by-byte. The only difference was the variable name assignment.

    6. Re: I just do some Python by Anonymous Coward · · Score: 0

      One class of 24, presumably mixed gender, which would result in 12 boys. Remove the 8 cheating boys and there would be 4 left. If the boy-girl radio isn't 1:1, then that group would be even smaller. Say it would be 14 girls as 10 to 14 isn't that unusual. That would result in 2 non-cheating boys. Yeah, the math based on the text in that comment adds up, or could add up and the feeling of isolation from the rest of the boys could be very real, particularly if those 2-3 boys not cheating didn't really get on well with each other.

      I'm not sure low self esteem shows from that post. Fighting the system and becoming an engineer would indicate quite the opposite. I read it more like still being upset with an unfair teacher and perhaps classmates.

      What strikes me is that the non-cheating boy shouldn't be suited for academic life while the cheating ones should. Did the teacher think the skill needed to gratuate from college should be cheating rather than studying? If so, it sure explains a lot about that story.

    7. Re:I just do some Python by Anonymous Coward · · Score: 0

      It would still be possible if the assignment was simple, but if that is the reason, then several would have handed in the very same code. They provided the evidence that they intended to cheat themselves. Using x as a variable is, well I might do that occationally, but only if there is just a single variable (like a short shell script) since x is the unknown in equations. However I can't think of any reason why I should use y as a variable unless x is already used. Since one person used y, it shows that he knew x was already in use.

      Actually now that I think about it, I do use x and y as variables quite a lot. One class to contain both provides a location, either on a map or on the screen. That would only make sense if they are stored as a pair, hence no reason to use that in the java code in question.

    8. Re:I just do some Python by Zeroko · · Score: 1

      When I was TAing, I had a pair of students submit very similar code, one in C & the other in C++, with printf vs. cout, swapping for & while loops, etc. But the overall control & data flow was identical. When questioned they insisted that the code was obviously not copied since it was not even written in the same language, & I tried to explain the concept of functional organization as separate from the exact text of the code, to no avail.

      (Not nearly as comical as the people who submitted screenshots that included microsecond-precision timestamps & screen glare (but slightly different cropping)...)

  24. All rules are not created equal by Xtifr · · Score: 1

    There are a lot of bad "rules" running around out there. There's also a lot of good ones. Some have evolved through painful experience; others are more like cargo-cult beliefs. But the bottom line is that we're all terrible judges of our own work. That's why authors need proofreaders and (frequently) editors. If you want to break something you think is a rule, for whatever reason, try checking with your cow-orkers, to see what they think about it. Yes, they may all be hide-bound idiots, but if you get hit by a bus, they're the ones who are going to be left maintaining all that code you wrote. And maybe, just maybe, they'll spot something you didn't.

    Yes, I know code reviews are painful and waste everyone's time, but spotting errors and issues up-front is orders of magnitude less painful than spotting them long after the fact, when the code has evolved to become several times more complex.

  25. #8 variable name length defines scope by avandesande · · Score: 1

    The longer or more descriptive the variable name, the wider the scope.

    --
    love is just extroverted narcissism
    1. Re:#8 variable name length defines scope by Anonymous Coward · · Score: 0

      The longer the variable name the wider the page.

  26. break, don't return. Better - while(&&) by raymorris · · Score: 1

    Combine that with another poster's 200-line methods and someone looking at the code has no easy way to know what the code returns - what it DOES . And the person looking at it my be you in two years. Also, such code -lies- about what it does. More on that in a minute.

    It is better to return at the bottom of a function, partly so you can FIND the damn return statement. So an improvement over return () in the middle of the function is to break.

    Even better, make the loop condition honest. Instead of this:

    while(line = readline) { ...
          if lineempty(line) return; ...
    }

    Do this:

    while( (line = readline) && line_not_empty(line) ) { ...
    }

    Now your while() condition is honest, it truly reflects how long the loop loops.

    1. Re:break, don't return. Better - while(&&) by Anonymous Coward · · Score: 0

      Your way:
      int value = someValue;
      if(someCondition) value = someOtherValue;
      return value;

      - Allocates a variable unnecessarily
      - Performs assignment twice

      The other way:
      if(someCondition)
                return someValue;
      else
                return someOtherValue;

      - Allocates no extra variables
      - Never performs an assignment at all

      One of these is objectively superior to the other.

  27. 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 Anonymous Coward · · Score: 0

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

      I've had to clean up after too many of these. The problem often boils down to it almost works, but cannot work reliably. Like, say, Office Automation from a server doesn't work. Well, you can hammer it and make it work, then when it's in production a few days it gums up because Excel opened a dialog box on session zero.

      Or more insidious, someone doesn't pay attention to idempotence and uses a stupid batch file to FTP billing records from one server to another. Then you get a whole day's charges duplicated. Fix the duplication bug, and get a loss bug. It doesn't work because the design is utterly wrong.

      Most of these rules exist for a reason, and they're to protect against having to debug some crazy unreliable nonsense in production.

    3. Re:The Issue with programming. by Darinbob · · Score: 1

      But just look at the rules listed. Some are just plain wrongheaded. As in "do not write your own data structures", as in no one should do that after their sophomore year. That's a stupid rule, people have to write data structures all the time. There are no libraries that do it for you that are the proper ones to use all the time; and even if there was one, *someone* has to write it and maintain it. The STL did not magically appear on Mount Sinai engraved onto tablets. I've got 20 KILObytes to work with, I need to be tweaking those data structures. "Breaking out of loops in the middle" - of course people do that, it's a waste of time and effort and code quality to stick in dummy variables just to avoid a break/return. "Using short variable names" - well duh, I get really sick of seeing code that has "for (innerIndexCounter = 0; innerIndexCounter size; ++innerIndexCounter)"; nothing wring with "i" or "ii". Code should be readable, and things that are too verbose are not readable.

    4. Re: The Issue with programming. by Anonymous Coward · · Score: 0

      I don't agree or disagree, however, you sound like a massive cunt.

    5. Re:The Issue with programming. by Hognoxious · · Score: 1

      Utter rubbish. I could write a novel following the of grammatical rules of English. Are you saying it would be the same as any other novel following the grammatical rules of English? Even if one was about KIng Harold and the other was about sentient turnips?

      If I wrote a program using no gotos, or only gotos, would it be the same as any other program using no gotos, or only gotos? Even if one was for finding prime numbers and the other was for finding duplicate files?

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    6. 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 *
    7. Re:The Issue with programming. by silentcoder · · Score: 1

      >I could write a novel following the of grammatical rules of English.
      I doubt that,, since you can't manage a sentence doing so.

      > Are you saying it would be the same as any other novel following the grammatical rules of English
      Human languages and programming languages are not comparable. Many things exist in human languages that do not exist (and where they crop up are actively removed from) programming languages. Nuance, metaphors, ambiguity, puns, double-meanings, irony, sarcasm, tone these are just some examples.

      > Even if one was about KIng Harold and the other was about sentient turnips?
      Aaah, plot... yet another one. That said, there are more than one kind of rule - and that GP was referring to the subset of those rules which are, in fact, most comparable to plot. I.E. which algorythms to use for which kinds of tasks. Which, if you follow them entirely religiously would mean you can ONLY write stories about sentient turnips or king Harold because writing about sentient potatoes is prohibited.
      Now the vast majority of times - those rules are actually worth following - nobody has yet found a legitimate use-case for bubble-sort, but they are not unbreakable and indeed, the start of our art only progresses by breaking them. Searching could never be faster than quick-search, until somebody added a new kind of algorithm to the table when parallel computing became practical (that the parallel and linear versions of quick-search are very similar and the ancestry is obvious does not change that the parallel version is, indeed, a new algorithm with distinct pitfalls, behaviors and things you need to be aware off - there are no race-conditions in linear code for example).

      > Even if one was for finding prime numbers and the other was for finding duplicate files?
      You're using a bad argument because you're looking at the wrong rule. How about the rule that says "this is the fastest algorithm for finding duplicate files" that rule can be mathematically proven right - but it doesn't mean it will STILL be right tomorrow, or that hardware changes will not mean that in a specific scenario a different algorithm may actually beat it. A device with peculiar read-write speed performance may actually perform better if you use a slower algorithm that allows slow seeks to happen while you're busy comparing previous results. Such a hypothetical storage device may not be common - but there are storage devices today with all sorts of variations in read/write/seek speeds (and filesystems adding their own factors on top of that). On a reiserfs file-system seeking through thousands of tiny files is fast, on most others it would be horribly slow.
      Just because the big-O notation proves an algorythm uses less CPU cycles, doesn't mean it's ACTUALLY going to be faster on EVERY piece of hardware, because CPU cycles do not exist in isolation.

      --
      Unicode killed the ASCII-art *
    8. Re:The Issue with programming. by Jane+Q.+Public · · Score: 1

      As in "do not write your own data structures", as in no one should do that after their sophomore year. That's a stupid rule, people have to write data structures all the time

      You're misinterpreting. "Do not write your own data structures" does not mean don't design your own objects, or structs, or whatever. It means don't don't try to second-guess your language by trying to create a new low-level structures like say a "character hash" with markedly different properties/behaviors from a regular hash.

      In modern languages, you'd almost always be wasting your time, and losing efficiency.

    9. Re:The Issue with programming. by RabidReindeer · · Score: 1

      Obviously you didn't RTFA.

      The rules in question weren't things like architectural standards and other things that can hobble solution of a problem. Unless your idea of a "solution" is simply "Git 'R Dun!"

      The rules that the article praised breaking were things like commenting your code (too much time and effort), defining data types (too much time and effort - let's see those pretty web page NOW!) and stuff like that.

      Rules, in other words, that are generally violated - and freely violated at that - by people who hack out software with blunt instruments instead of "wasting" time on producing something that's reliable, secure, and easy/inexpensive to maintain and debug.

    10. Re:The Issue with programming. by Anonymous Coward · · Score: 0

      The end user doesn't care about form, they care if it Works well, It can be maintained, and it is secure.

      In my experience they usually they only care if it works at all...

    11. Re:The Issue with programming. by parkinglot777 · · Score: 1

      The rules that the article praised breaking were things like commenting your code (too much time and effort), defining data types (too much time and effort - let's see those pretty web page NOW!) and stuff like that.

      The explanation of this rule breaking in TFA is partially true. You may not need to over document variable names because they tend to be (and should be) self-explained. However, for a method and/or function, one SHOULD document what the method is EXPECTING (inputs) and how it does/returns (if any). In other words, use white-list approach, not black-list, in the documentation. TFA excuse (not reason) is that it is over documented because sometimes the documentation is for previous 4-5 versions. That is NOT an over documentation issue, but it is the LAZINESS of the programmer/developer to not update the document.

    12. Re:The Issue with programming. by RabidReindeer · · Score: 1

      Actually, I suppose that what really grates on me on the comments issue is that I was doing "literate programming" long before Knuth named it.

      In other words, the comments go in first and they explain WHAT the code is going to do. Then I wrap code around them to do it.

      Those are fundamental attributes of the function and while details change, this kind of comment doesn't go out of date nearly as fast as the "add 1 to X" type comments that say HOW the code does it. And the code is IMHO better quality because I have mapped the forest before I started laying in all the trees.

      The how-to comments can end up being more trouble than they're worth, and on that, I'll agree that sometimes it's better to just skip them. The WTF am I doing? comments often mean I don't need many, if any how-to comments. And since my basic code design is based off them, I don't skip them.

    13. Re:The Issue with programming. by Darinbob · · Score: 1

      But you need to do this in many situations just to reduce code size or efficiency. STL is bloatware, it won't fit on many embedded systems. Anyone can and should be able to write a simple linked list or doubly linked list. Any RTOS will have their own list structures and not rely on some third party library. Anyone building a file system will essentially design their own data structures (with disk as the storage instead of RAM). Anyone actually writing the language or the language's run time system will obviously have to write the data structures.

      For example, C++ does not have any hash built in. It's map is a binary tree, but hashes can be better in many cases (though I have seem some people argue that the trees are "optimal" which just means they skipped their theory classes). The built in data structures are optimized for the general purpose case.

      But it's true, if your job is very high level code, such as some web app stuff, then don't write your own data structures without a good reason. But you should know what they do so that you know how to use them efficiently (ie, knowing when to use a list versus an high level array versus a primitive array, even though they're interchangeable in many cases).

      When I interview poeple I ask about data structures. I have to because that's going to be a part of the job, they will have to deal with linked lists. But I get candidates that say "oh, I usually use a library for that", which means they'll be useless in that area. If they can't work through something so simple then how are they going to react when they have to fix a bug that involves lists? I am utterly amazed at how few candiates with lots of "embedded" experience are clueless about such simple concepts.

    14. Re:The Issue with programming. by Darinbob · · Score: 1

      Of course, you can do however you want in Python, it is only the modern Python community that has generated these rigid rules.

      Python is a scripting language, which means that it should not be as rigid and structured as a traditionally compiled language. Enforced private data is ok in languages like C++, even in many interpreted languages, but it feels out of place for a scripting language. Except that what was once sort of a replacement for Perl has grown into something used in serious production applications.

      From the very start with Smalltalk, making your own data structures with object oriented languages has been the norm. Sure there may be a large built in collection of data structures but they usually came with means of subclassing from them, extending them, customizing, etc.

    15. Re: The Issue with programming. by Anonymous Coward · · Score: 0

      WHAT and HOW are often the same. Good programs are logical decomposed and symbols clearly named such that the code explicitly tells you WHAT. Comments should be used to tell you WHY it is doing what it is.

    16. Re:The Issue with programming. by penguinoid · · Score: 1

      There are things that are impossible in computer science, e.g. solving the Halting Problem.

      echo "The program will halt."

      --
      Don't waste your vote! Vote for whoever you want, unless you live in a swing state it won't matter anyways
    17. Re:The Issue with programming. by silentcoder · · Score: 1

      Python has been a lot more than "scripting language" (at least in the sense you use it) for a very long time.

      --
      Unicode killed the ASCII-art *
    18. Re:The Issue with programming. by burbilog · · Score: 1

      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.

      Well, I did the same for many years. Now I'm sitting there and think "what the fuck? why, oh why I was SOOOO smart and implemented that 'impossible'???? what for?!".

      Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?

    19. Re:The Issue with programming. by greysondn · · Score: 1

      It must be able to solve for any program body input whether or not the program will eventually halt. You fail to even parse input here and determine it.

      We can sidestep some of the ramifications of the Halting Problem by saying "it won't halt within x amount of (real) time" or "it won't halt within x iterations of the core loop we're concerned about". I can't swear to it, but I'd think a good process manager would use some system based on these ways of looking at it to tell if a process is hung. (Yet somehow Windows often catches processes that aren't hung at all and tries to tell me they're "not responding".)

      In the real world, these solutions - that we can guarantee if it should halt or not within some span of realtime - are often "enough", even if they're not "technically a solution to the halting problem". This is because most tasks in the real world are deadline oriented anyway in some fashion (and when they're not, they're often "limits of human patience" oriented).

    20. Re:The Issue with programming. by Anonymous Coward · · Score: 0

      I think he means the program WILL halt eventually.

    21. Re:The Issue with programming. by Jane+Q.+Public · · Score: 1

      But you need to do this in many situations just to reduce code size or efficiency. STL is bloatware, it won't fit on many embedded systems. Anyone can and should be able to write a simple linked list or doubly linked list.

      I agree with you. But the point was: usually when using modern high-level languages (as opposed to embedded systems) you're wasting your time. Sure, you ought to know how.

      But it's true, if your job is very high level code, such as some web app stuff, then don't write your own data structures without a good reason. But you should know what they do so that you know how to use them efficiently (ie, knowing when to use a list versus an high level array versus a primitive array, even though they're interchangeable in many cases).

      Yes, unless I am mistaken this was the context of the original quote. But again I agree that you should have the theory and experience to do it if/when necessary.

  28. Not handling error conditions by Anonymous Coward · · Score: 0

    The greatest sin I seen (in my code and that of others) is to focus so much on making the normal/success case clear and simple, that the error/failure case becomes even more difficult to follow. In many ways exception handling is a feature designed to encourage this mistake, since all that checking return codes made things complicated.

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

  30. Allman style braces by Anonymous Coward · · Score: 0

    I use Allman style braces.

    https://en.wikipedia.org/wiki/Indent_style#Allman_style

    I have found that the ease of being able to visually line up matching braces in the same column beats the fact that the resulting code uses a few more vertical lines. This is a judgment I have come to after 25 years of seeing both styles extensively in use. I use this style in every language that has braces, including JavaScript.

    1. Re:Allman style braces by Anonymous Coward · · Score: 0

      Tabbed Whitesmith's. I know a lot of people have looked at my code and hated it; but lined-up braces beat the shit out of vertical compactness, and until all the common editors default to letting me leap through spaces 4 at a time with a singe keystroke, I'm tabbing.

    2. Re: Allman style braces by Anonymous Coward · · Score: 0

      I used to do that, but frankly opening braces on the line the block starts is much cleaner. Modern IDEs all have code block collapse and visual cues to find matching braces in both directions, so I find adding more lines just adds clutter.

      Btw who ever invented the term vertical line? Lines in code are horizontal, for crying out loud!

    3. Re:Allman style braces by Anonymous Coward · · Score: 0

      I use Allman style braces.

      https://en.wikipedia.org/wiki/Indent_style#Allman_style

      I have found that the ease of being able to visually line up matching braces in the same column beats the fact that the resulting code uses a few more vertical lines. This is a judgment I have come to after 25 years of seeing both styles extensively in use. I use this style in every language that has braces, including JavaScript.

      I agree. Give me Allman-style braces or give me death.

  31. Re:No "new" by deKernel · · Score: 1

    I really hoping you are being sarcastic because if not, you really haven't worked on any projects of real size. What you describe is really nice for an app that does addition and subtraction, but when you have connections with multiple databases, have several dozen static sockets connections going while processing messages from those sockets, your suggestion of not using objects is naive at best.

  32. tools, not rules by anyaristow · · Score: 1

    I see a lot of rigidity around buzzwords and established practice, because programmers these days are given tools, and to appear smart to other programmers, they treat these tools as rules. As if knowing some rules is more important that solving problems and getting the job done. It's apparently easier to show how smart you are by regurgitating rules and criticizing people who don't follow them rigidly than it is to actually accomplish things.

    1. Re:tools, not rules by ilsaloving · · Score: 1

      You're attitude is exactly the reason why the vast majority of software projects shoot past deadlines and budget, and result in shockingly substandard quality products.

      You really think these "rules" are just some form of elitism? Best practises have come about after decades of learning from past mistakes. They are there to help improve programmer efficiency, improve teamwork, improve product quality and maintainability. I've lost track of the number of times where I have personally seen someone take some kind of shortcut to "save time", only to have it bite them in the ass later and require hours if not days to fix.

      So if you honestly think that you're too good to have to subject yourself to something inconvenient like "Rules" and "Best Practises", then please do everyone else a favour and stay away from anything even vaguely resembling programming. You'll be doing the rest of us a huge favour.

    2. Re:tools, not rules by Anonymous Coward · · Score: 0

      It is because they are shit at solving problems, I see it also in various types of table games involving rulebooks. As the ego of them is invariably greater than the competence, they cling rigidly to the rules to appear competent

  33. I just do some Perl by xanthos · · Score: 1

    Using Perl pretty much covers all nine and then some.

    Except, perhaps, for #5 Yo-yo code. That is actually a built-in feature.

    --
    Average Intelligence is a Scary Thing
  34. I repeat the "this" keyword often, intentionally. by Anonymous Coward · · Score: 0

    I refuse to use class member functions or variables without the "this" keyword despite everyone telling me it's not needed.

    I'd rather pollute the body of member functions with this->some_variable against just writing "some_variable" and expecting the reader to know if that's a member or global variable. Especially if it's a member inherited and not directly on the class where it's used.

    I also refuse to use globals, or interact with any C api without first wrapping it in a trampoline that calls right back into C++ member code, properly wrapped with cleanup code and a smart pointer.

    My USD $0.02c

  35. Re:No "new" by alvieboy · · Score: 1

    Of course I was being sarcastic. Pretty much obvious, don't you think ?

    But still - on Embedded world you can do much without relying on dynamic allocation (and the expensive free). Just needs careful sizing and requirements analysis.

    Alvie

  36. C++ macros by Anonymous Coward · · Score: 1

    Add macros to the list. After inventing template types which shoehorn macros into the string C++ type system, dogmatists decided that the rest of the cases handled by preprocessor macros are somehow evil. Don't listen to them.

    As for gotos. Linux driver people use them to clean up after jumping out of a sequence of system calls. I imagine BSD folks do as well. They use them like simple exceptions. Intent is clear and simple. I have no problem.

  37. Re:No, I *don't* secretly love by Anonymous Coward · · Score: 1

    You seem a bit upset. Step outside and sniff a flower.

  38. All my indexes are i, j, k by default. by mveloso · · Score: 1

    All my indexes are i, j, k, etc unless there's an actual reason for using a real index name.

    Sometimes, I just want to fucking iterate without having to come up with some kind of descriptive name that's ultra-long and verbose. I'd use foreach if the language supports it...but it doesn't.

    1. Re:All my indexes are i, j, k by default. by ilsaloving · · Score: 1

      Personally, I see no problem with this, because using i, j, k have been used as iteration variables for decades. In fact, I have never once seen a classic example of iteration that *doesn't* use them.

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

    3. Re:All my indexes are i, j, k by default. by Anonymous Coward · · Score: 0

      Some of the older web forums had this habit to change i to Italic if used in a specific way. It hit all for() loop codes, because i was the most used variable name in for(int i= ...

    4. Re:All my indexes are i, j, k by default. by Anonymous Coward · · Score: 0

      n was often used in Sinclair Basic because NEXT was on the n key, and loop variables could only be one letter.

    5. Re:All my indexes are i, j, k by default. by Anonymous Coward · · Score: 0

      I don't know about shot, but maybe waterboarded.

    6. Re:All my indexes are i, j, k by default. by Anonymous Coward · · Score: 0

      I often have indices for several different arrays at once, and it can be helpful to use subscripted indexs:

      for i_x, x in enumerate(positions):
              for i_t, t in enumerate(times):
                    result[i_x, i_t] = something

      That's more descriptive than i, j, k, but still obviously an index of some kind.

    7. Re:All my indexes are i, j, k by default. by cellocgw · · Score: 1

      All my indexes are i, j, k, etc unless there's an actual reason for using a real index name.

      Until you're forced to use MATLAB and suddently discover that BOTH i and j are defined as sqrt(-1) and you've just overloaded these definitions, quite possibly breaking some lines elsewhere that invoke complex numbers.
      Yes, that's MathWorks' fault. Just be careful out there.

      --
      https://app.box.com/WitthoftResume Code: https://github.com/cellocgw
  39. Adding ints in C by CODiNE · · Score: 1

    Yeah I just add int1 and int2 without even worrying about overflows. But so does everyone else. :-/

    --
    Cwm, fjord-bank glyphs vext quiz
    1. Re:Adding ints in C by Anonymous Coward · · Score: 0

      FYI: gcc now has integer overflow builtins

  40. Re:I repeat the "this" keyword often, intentionall by Anonymous Coward · · Score: 0

    The habit is pedantic, craps up the code, generally loses. When I encounter it, it is easy to fixed with a single replace. Globals (singletons) have their place, especially for map lookups, unless you prefer needlessly decoding argument references.

  41. Re:No, I *don't* secretly love by Anonymous Coward · · Score: 0

    Eh.

    I work with a lot of third-party code. A large framework that violates as many of these rules that are relevant to the platform, and adds a ton of new platform- and domain- specific annoyances.

    It is what it is. At least bad code is still code. You generally have defined conventions and the tools available to track down problems, even if it is frustrating. (Not so with client expectations!)

    Moreover, more and more code is, quite frankly, disposable. Only the business requirements need to be well documented because everything else is going to churn within 2 years. These problems are only going to get worse, and a "good" programmer will be one that can still work efficiently within the chaos.

  42. Re:No, I *don't* secretly love by ilsaloving · · Score: 1

    I do get upset when I see idiotic articles like this. It implies that these "habits" are acceptable, when in fact they should be avoided unless you have a very good and specific reason to do so. For things like documentation, there is NO conceivable excuse to justify being so lazy as to not being willing to add a quick blurb about what your routine does, *especially* when it's doing something unusual.

  43. Making bugs by Anonymous Coward · · Score: 0

    I have the bad habit of adding bugs when I write code. I must be absent minded or something while writing code because once I'm done and detect that there is a bug, I can never remember adding it. Sure I fix the bugs before you ever encounter the code, but just think about how much time I could save by controlling this bad habit. If anything, that got to be the worst bad habit of programming ever.

  44. Not splitting short articles over two pages by Anonymous Coward · · Score: 0

    That is one rule no-one with any pride in their work would break, unlike, ooh, say ...

    Money grubbing buggers.

  45. self-documentation by Spazmania · · Score: 1

    Many functions and even some classes are more or less self-documenting. Functions with names like insertReservation or cancelReservation or deleteAll don't need another line or three to explain what's going on.

    An undocumented function with well chosen names is like a sentence with only nouns. You might, if you're lucky, get the gist of it but those missing verbs and adjectives would really have been helpful.

    --
    Moderating "-1, Disagree" is simple censorship. Have the guts to post your opinion.
  46. My mistake by prefec2 · · Score: 1

    I read the article. Honestly, it sucks. And I should have known it. Anyway, to let come something good about it, here are his arguments:
    a) gotos are only a problem when the result in entangled code and in some cases they make code more readable, because you may avoid if-then-else trees.
    - This is wrong for a number of reasons: Too many nested if-then-else result in too much complexity and violate another coding style, ergo such structures are already bad in the first place, to fix them with a goto makes things not better.
    - Many languages used nowadays do not provide a real goto. Even though Java has jump labels, but should not use them!!
    b) Commenting all functions is wrong.
    - Well this is true, however, it is also not a rule. It was a rule in the days where your function names where limited.
    - You should document functions which have side effects, and you should document the purpose of classes, modules, etc.
    - Never document after writing. Write the documentation first, let it explain what the implementation should do and why, then write the code, then fix the documentation
    c) Jamming too much code on one line, i.e., do not write component.interface.orderSushi()
    - I do not know where the guy is from, but that is not against any rule
    - While he is right here, which jerk still uses such limitations? Checkstyle, PMD, and Findbugs have no problem with what he wants. And yes your line should not be that long that you cannot see the whole statement/expression.
    d) Not declaring types, he means not using types for declaration
    - In languages, like C and Java you must give variables a type
    - in Xtend the type can be inferred in many cases, then you can skip them in the definition. Yes you can, however, sometimes it is still more useful to type explicitly, because it prevents a variable or value to be used in the wrong way.
    e) Yo-yo code, he means do not convert numerical values to string to pass them to some code and convert it back afterwards
    - This is a perfect and good advice. Actually, it is an advice for a moron. You NEVER do that.
    - However, it makes sense in his example, because if you are ordered to use a library which uses strings you must convert, but that is not a violation of the do not make stupid moron code, it is the "bad luck, you have to interface with some moron's library" situation.
    f) Writing your own data structures is a bad choice
    - First, this is utter nonsense, we write new data structures for every program. Where is this guy from?
    - Second, he means storage routines. Well that depends. If you want to write your own OR-mapper then that is a wast of time. That will never be faster and never be able to work with any scaling technology.
    - Third, I cannot see a real clear argument in that section, but maybe he is right, because it is Tuesday.
    g) Breaking out of loops in the middle
    - That depends on the language. If your language has no garbage collection mechanism or you passed references to data and changed it, such jump out could leave you with an incomplete state. However, we do not teach that this is illegal or bad practice, as we teach Java at university. It could be stupid, if this results in a lot of code duplication in the dependent return (if (bla) { code; return rubbish; }
    h) Do not use short variable names
    - Yes you should not use short variable names, when they do not express what the variable does.
    - However, i,j,k are iterator variables. We know them from math.
    - In contrast f is not a good variable name (in most cases) so better call it fartCounter or even better countFarts, depending on the purpose in your game
    i) Redefining operators and functions is evil
    Yes it is. And no there are no good reasons to do so as a programmer unless your redefinition is WELL documented and stays the same in the whole program. It is already stupid that Java uses the plus sign for String concatenation. Especially, because String is a calls in Java and not a data type. However, it sucks even more if the + sign or * sign is redefined and means one time multiplication of two scalars and the time it is a cross product.
    It might be more code to type (or to provide by the IDE) to actually write a function name, but please do so, it increases readability.
     

    1. Re:My mistake by Anonymous Coward · · Score: 0

      mm, congratulations you are the moron!

      you believe you know more than you actually do!

      Stop following the hype trains.

    2. Re:My mistake by mark-t · · Score: 1

      By far, the single biggest problem with comments is that they lie.

      Someone write the comment, and then the code later evolves and changes, and a programmer forgets to update the comment. This happens *ALL OF THE FUCKING TIME*. While some types of comments, such as dOxygen or javadoc may be able to peform very rudimentary verifications that the code has not changed beyond what the particular formatted comment would describe, it is not possible possible to for a compiler to generally verify that a particular comment still carries the same meaning that it did about the code when it was first written. A wrong comment is orders of magnitude worse in terms of the costs to productivity than no comment at all.

      Writing good comments, therefore, is a discipline that is arguably harder than programming itself... since one must not only have the discipline to program in the first place, but must also maintain the discipline of keeping the documentation up-to-date and informative.

    3. Re:My mistake by Stonent1 · · Score: 1

      d) Not declaring types, he means not using types for declaration - In languages, like C and Java you must give variables a type

      What about :
      var something = somethingElse();
      Sometimes you're dealing with some kind of method that uses some type you're not really familiar with other than you can access a few methods attached to the returned data to get what you need.

      You're technically not giving it a type, your'e just letting it figure it out via var.

    4. Re:My mistake by mark-t · · Score: 1

      i) Redefining operators and functions is evil
      Yes it is. And no there are no good reasons to do so as a programmer unless your redefinition is WELL documented and stays the same in the whole program. It is already stupid that Java uses the plus sign for String concatenation. Especially, because String is a calls in Java and not a data type. However, it sucks even more if the + sign or * sign is redefined and means one time multiplication of two scalars and the time it is a cross product. It might be more code to type (or to provide by the IDE) to actually write a function name, but please do so, it increases readability.

      Which is easier to read?

      n = a.subtract(b).multiply(c.subtract(d))
      or
      n = (a - b) * (c - d)

      If you seriously think that the first one is more readable than the second one, then consider this.... do the 'subtract' and 'multiply' methods modify the contents of their class instance, or would it have been better to name it 'minus' and 'times'? The naming of the methods the former way strongly implies that it modifies the instance, and this will not be clear to a reader who is expecting the code to simply say what it doing in a clear and unambiguous way.

      Yes, I will certainly agree that operator overloading generally only makes much sense in very mathematical contexts such as what I have given above (I have often cursed Stroustrup for setting a bad example in the early C++ days by overloading the bitshift operator to do I/O.... convenient, sure.... but completely counterintuitive to the normal meaning of the operator). I would argue, however, that since programing *IS* math, this kind of thing happens a lot. And since are infinitely more mathematical types than just what programming languages might offer built in (complex, vector, quaternion, matrix, and many many more,)... for vectors and matrices, there are often performance considerations to using a general class as opposed to one that is optimized for a data structure of a specific size, so there are infinite variations on just those two particular data types.

      The biggest problem with operator overloading is that it is abused by programmers as a shorthand for something that has nothing to do with what the operator ordinarily means (eg, > in C++), but I strongly argue that suggesting that it has no place in programming because of that is akin to suggesting that programmers should not be allowed to choose their own identifiers on variables or functions names on account that they might also be misleading or cryptic.

    5. Re:My mistake by Lord+Bitman · · Score: 1

      The only thing that should be commented is the "weird why".

      For example: "We convert this number to a string here for compatibility with the called library, which expects to handle Big Numbers generically." or "Yes, this is completely stupid, but is required due to an unknown bug. For reasons which have yet to be understood, this code causes a segmentation fault (traced all the way back to llLib-Foo), if this method is not called twice. The resulting output is (mathematically) equivalent, though expectedly weird-looking. As llLib-Foo is only called after seven levels of indirection (six of which, we have absolutely no control over), we are at the mercy of upstream to provide a fix. For now, this appears to work."

      The best place for all other "comment"-style documentation is the commit log, where it will be forever associated with exactly when it was written, and what the code looked like at that point.

      --
      -- 'The' Lord and Master Bitman On High, Master Of All
    6. Re:My mistake by Anonymous Coward · · Score: 0

      By far, the single biggest problem with comments is that they lie.
      Someone write the comment, and then the code later evolves and changes, and a programmer forgets to update the comment.

      Uhm, I hate to break it to you, but this is the code lying, not the comments. You should always treat the comments are truth and then update the code accordingly. Whenever there is a discrepancy, first alter the comment (if needed) and then fix the code to match. Your life will be much happier once you realize that this is The Way.

    7. Re:My mistake by mark-t · · Score: 1

      I hate to break it to you, but that never really happens. Further, code says what is *actually* happening. Comments can indicate intent, but intent means zilch if you don't actually go and do it. Code cannot lie... At most it can only fail to fulfill the expected requirements,

    8. Re:My mistake by mark-t · · Score: 1

      Except that never actually happens on any project more complex than a school programming assignment.

      Code says what actually happens, not comments. At best, code can only break promises that moment make, but intThe end such comments are still ultimately lying, even if through no fault of their own.

      The only way the code can lie while the comments tell the truth is if the computer executes the comments and not the code. Hmmm reminds me of COBOL.

    9. Re:My mistake by prefec2 · · Score: 1

      A method should not evolve in something that does something completely different than before. Lets say it is labelled collectAllCustomers than it should do so. It should not start to collect only a specific group of customers. If the method has side effects which effect other methods behavior than this should be mentioned (if it is not plain obvious, like with getters and setters).

      However, I absolutely agree with you that some "programmers", I would rather call them code monkeys, do not know what they do and they fuck up code beyond repair, which includes code comments and also documentation. Yes it is faster to not document decisions or even decide as you go, but later when you need to change it again, it is much harder to find out what the stuff does.

    10. Re:My mistake by prefec2 · · Score: 1

      Totally! Ahm. I agree with your assessment.

    11. Re:My mistake by mark-t · · Score: 1

      A method called collectAllCustomers should not require a comment explaining *what* it does. What the method does should be transparently obvious from the name. Ideally, how it goes about this should be equally transparently obvious from the code itself by keeping the method concise, and using well named identifiers.

  47. procedural code by Anonymous Coward · · Score: 0

    i write php, mainly for my own use (a little for the web). i even use it as a replacement for bat files in windows (file manipulation and such, not interfacing with windows like bat/cmd can). i use procedural code a lot. essentially only using oop when existing libraries i'm using are built that way. and i dont give a shit what people think, because it's for me, my stuff isn't complex, and it's easier and faster to produce.. if procedural code wasn't "good enough" languages would no longer support that method.

  48. Re:No, I *don't* secretly love by Anonymous Coward · · Score: 0

    You are right in everything you say, and you sound like a self righteous prick. Guess what? I'd fire you in a heartbeat.

    Code: I can help you fix coding habits.

    Attitude: Everyone's happier without it.

  49. only 1 rule! by Anonymous Coward · · Score: 0

    presume 99% of other programmers are idiots!

    never failed me yet!

    and yes, you are the 99%.

  50. modern programmers are dumb as rocks. by Anonymous Coward · · Score: 0

    You should all be forced to work with computers with too little memory and slow processors.

    You might learn how to produce efficient, fast and small code.

  51. database table names by Anonymous Coward · · Score: 0

    Sometimes I name database tables in plural if the singular name ends up being a reserved word in SQL (ie. 'orders') and I do it because I'm sooo damn lazy but it does make writing queries easier. I'm so ashamed so posting as anonymous coward.

    1. Re: database table names by Anonymous Coward · · Score: 0

      Clearly, if your still naming database tables you are doing something seriously wrong. Ever heard of ORMs?

  52. The article's author, by Anonymous Coward · · Score: 0

    Peter Wayner doesn't have a clue about programming. Why is he publishing articles on the subject? Hint: TRUE and FALSE are not keywords in Python, and you can do the same ting in most other languages too. It's just stupid though and no sane dev ever does it. Way to go, Wayner.

  53. Long ternary statements by Dixie_Flatline · · Score: 1

    I love a good ternary. I find it really obnoxious to try and set a variable through a long set of if-then-else statements, and sometimes I'm forced by C++ const correctness to do it through a ternary anyway.

    I do my best to break them up over multiple lines in a way that makes the structure obvious, and I document them so you can read the comments instead of reading the actual code, but I know that's vulnerable to comment-rot.

    To a certain extent it's a bad practice, but I really do find the terseness of a ternary a lot more pleasant. (If I have to do it more than once, I just make it a function, obvs.)

  54. replied to wrong post? by raymorris · · Score: 1

    Did you reply to the wrong post? I posted about a loop, you posted about a conditional.

    Your post contains no loop, and mine doesn't assign twice.

    Or are you referring to the fact that in order to return at the end, one might have to assign the return value to a variable earlier. That's true. Compare spending 1/1,000,000,000 of a second processing time versus both spending 30 minutes of developer trying to figure out what it's supposed to return time AND increasing the likelihood of a bug affecting customer data. One is clearly better than the other, certainly.

  55. Re:No, I *don't* secretly love by ilsaloving · · Score: 1

    How exactly is it self righteous to expect someone who claims to be a software developer, to actually be skilled in that field?

    How is it self-righteous that a client's project is gonna crash and burn because they are using developers that *don't* follow best practises, and end up vomiting some kind of nonsense that vaguely resembles intelligible code?

    I've HAD people fired for being grossly incompetent, to the point where they were a threat to the project. And you know what? They were perfectly nice and friendly people. That doesn't change the fact that they shouldn't have been allowed anything more sophisticated than a burger grill.

    So yeah, I dunno if you're actually a project manager or just some AC putting on airs, but if you would rather ride your mission critical project on someone who was "nice" rather than someone who actually knew what they were doing... Well... I look forward to reading about your projects on The Daily WTF.

  56. Re:No, I *don't* secretly love by Anonymous Coward · · Score: 0

    To actually be honest (same AC as @3:59PM), I agree with most of what you said. Not all the "habits" in the article are actually necessarily evil - for instance, I very often do multiple returns from a method, not least as those methods tend to be about ten lines long and the whole thing is in your face at the time. I disagree with coating code with comments, but *definitely* agree that anything non-standard, obtuse or unexpected bloody better should be commented and I get at least reasonably angry when it isn't.

    We have methods that are ultimately, A = B + C * D, where A and B are 1 x n vectors, and C and D are matrices n x m and 1 x n matrices respectively. These methods span thousands upon thousands of lines, and I'm fairly sure that some careful usage of boost::matrix would reduce them to about 30. If there was a reason to make them so absurdly overcomplicated, it should have been explained. It wasn't, and it's a source of confusion and bugs to this day.

  57. Braces by MouseTheLuckyDog · · Score: 1

    I never put braces around one line stements in for example if statements.

    if(a==b)\
    {
          do_a_equals_b();
    }

  58. compile bait? by TiggertheMad · · Score: 1

    I feel an overwhelming urge to expand and read these functions....well played, sir.

    --

    HA! I just wasted some of your bandwidth with a frivolous sig!
  59. hmmm, could it beeee... by r-diddly · · Score: 1

    ...that there's no universal principle or rule that's always true? Could it be that the best thing to do in a given moment, is to do the best thing in the given moment? naaaaahhh....

  60. Re:No "new" by r-diddly · · Score: 1

    Hmm speaking of bad code... replies linked to the wrong comment. Nice.

  61. whot by Spaham · · Score: 1

    what rules, to begin with ?
    Do you always solve the same problem ??

  62. I will never "write my tests first" by Lord+Bitman · · Score: 1

    If I know exactly what someone wants, then sure: write the tests first, that makes sense.

    But the vast majority of the time, fulfilling a requirement is just as much about finding what the person *really* wants, as it is about finding out how to supply it.

    By the time I know what the question is, the answer has already been written.

    It's only at that point that I have the ability to rigorously test the implementation of that answer.

    --
    -- 'The' Lord and Master Bitman On High, Master Of All
    1. Re:I will never "write my tests first" by Anonymous Coward · · Score: 0

      Being unable to write the test first shows lack of details from the code planning stage. Depending on what you do, it might be just fine or horrible. Firmware for pacemakers or train brakes would really require you to know the demands first and well enough to write the test first. If you just write some open source game as a hobby in your spare time, then it likely isn't really an issue. Anything in between (that would be most software), do consider if the plan is good enough to provide a trustworthy result.

      I have a worse confession. I tend to skip automated tests entirely if I do something on existing existing software, which doesn't already have automated tests. It's often too complex to add after 50-100 people contributed several parts over the years with no test friendly structure in mind. It bothers me a bit because I can see it affects reliability, but I'm not really sure what to do about it.

  63. Roughly what I would have written by grimJester · · Score: 1

    Although I was unaware Java had those labeled jumps. Funny, given that I've been a Java coder the last 15 years.

    A Stackoverflow answer had a decent example of where they could be used; a straightforward nested loop that quits when it finds something. Especially with foreach that doesn't look too bad.

    search:
    for(List<String> names : groupNames) {
    for(String name : names) {
    if("joe".equalsIgnoreCase(name)) {
    break search:

    Horrible? Maybe if the average coder hasn't seen labeled breaks before...

    1. Re:Roughly what I would have written by Anonymous Coward · · Score: 0

      for and if aren't functions. Please don't write for( and if(. Write for ( and if ( like normal people. Thanks.

  64. This Artilce in a Sentence by Anonymous Coward · · Score: 0

    Common sense trumps absolute rules.

  65. I use helper classes. Builder classes. by 140Mandak262Jamuna · · Score: 1
    Our company rule is one class per header file, one source file for its implementation. For some of the top level classes that manage the entire product, I would dedicate a whole source file for one function of that class! Violated one source per class. That function will be in a file with a private helper class that will build all the temporary data structures and methods to implement it. A class and its implementation in the file that implements just one function of a higher level class. These single function calls would be something like product::CalculateRadarCrossSection(); . The function might take several minutes to a few hours to execute, it will instantiate an instance of a class not visible outside that file. The helper class would build elaborate data structures, maps and multimaps etc, calculate the radar cross section and clean itself of all the temp data in the end.

    I use builder classes, which apparently a big violation of C++ style guides. For example class StiffnessMatrix would provide lots of services and provide methods to interact with other instances of StiffnessMatrix. But it will be built using a class StiffnessMatrixBuilder. I don't know people say things like "a well designed class would not need a builder class".

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  66. All code looks bad by Anonymous Coward · · Score: 0

    without a 4K monitor.

    I can now compare whole code segments, in many instances, side-by-side in full, and my brain loves me for it.

  67. Guilty of #3 by Jeremi · · Score: 1

    My bad programming habit is #3 -- putting too much code on one line.

    The problem I have is that the there's no standard terminal width anymore. Back in ancient days, it was simple to say "just try to keep lines less than 80 characters long so that the fit nicely on the VT100 terminal everybody uses", but now that most developers have monstrous 30" LCD screens running a 4K resolution, etc, an 80-character line-length limit is a ridiculous underutilization -- like formatting a newspaper so that it can be easily read through a periscope, even though nobody ever uses periscopes for that purpose.

    So the next thought would be, choose a line-limit greater than 80 characters long. But what? 160 characters? 320? Whatever number of characters fits across the width of a "typical" window? What constitutes "typical"? And at what font size? Fixed-space font or proportional?

    At that point the Asperger's-compliant section of my brain says "ah, screw it, it's all subjective anyway", and I just end up ignoring display-width issues and just putting as much on the line as will logically go onto the line. vi (the only editor worth considering ;)) handles line-wrapping just fine, so it's not a problem for me. It does irritate my co-workers who are using non-line-wrapping IDEs though, since they have to do a lot of scrolling back and forth. (Of course that has the benefit of training them to leave my code alone if possible, which shouldn't be overlooked)

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  68. Please don't use single letter variables by fhriley · · Score: 1

    I don't care if your variable is a loop variable or a simple array. Ever try searching code for a loop variable "i". Yeah, that's why you don't do it. At the very least, name it "ii".

    1. Re:Please don't use single letter variables by ayesnymous · · Score: 1
      > Ever try searching code for a loop variable "i"

      Yeah I search for \<i\> all the time. Either that or search for i while checking the "Whole Word" box.

    2. Re:Please don't use single letter variables by Dog-Cow · · Score: 1

      Search for " i " or "(i ", if you need to find where it's not used as an index; otherwise, use the obvious "[i]".

      It's not really hard. And if you have to scan more than a dozen lines to find users of a specific loop variable, your code is hopeless crap.

  69. Undo incorrect moderation by kjots · · Score: 1

    This comment brought to you by Slashdot's baffling omission of an 'Undo moderation' feature.

  70. refactor by Anonymous Coward · · Score: 0

    I break the rules if I am out of time and result is better than before. E.g. I refactor without writing new tests.

  71. Doesn't always help. by Chirs · · Score: 1

    Comprehensive unit tests don't help when the thing only breaks in integration testing.

    Maybe the sqlite database you use in your unit tests behaves slightly differently than the PostgreSQL database you use in production.
    Maybe the refactored code adds a race condition that the unit tests don't cover.
    Maybe the refactored code runs slower in certain scenarios that turn out to be important.
    Maybe the unit tests missed a corner case.

    Sure, in an ideal world these wouldn't happen. But they do.

    1. Re:Doesn't always help. by dave420 · · Score: 0

      It seems you don't really know how to write or run tests...

    2. Re:Doesn't always help. by Junta · · Score: 1

      Automated testing is valuable, but not perfect in practice. For most real code, you cannot hit every possible set of inputs, and settle for only the ones folks realize are 'interesting' (given that for much code, the set of inputs is in fact theoretically unlimited). Generally those tests accumulate over time as real-world defects drive recognition of "oh, yeah, another 'interesting' case we didn't consider before". 'Comprehensive' is generally not a possible absolute goal. I know a lot of folks who genuinely believe now that we have a paradigm of automated unit tests and test driven development, there is no longer a need for maintenance branches or more real world testing than what happens in response to a commit. Amazingly, this frequently continues even after several instances in their 'comprehensively covered' unit test project having reported bugs when going to production, dismissing those bugs as 'really freak situations'. It doesn't help that people celebrate declaration of '100% covered' in unit tests, as if that is some milestone that makes bugs totally impossible then.

      Now it can be that for a very simple function, the practical risk of missing unanticipated scenarios is low. However, I was speaking to a function that you end up duplicating and refactoring without perturbing the original instance, instead of refactoring that too. In that scenario, if it does *almost* what you need but not quite, it's almost certainly in the class of functions that existing unit tests do not provide 100% coverage.

      If you break critical production code that has been doing it's job for several years, not because it had a different problem that was trying to be fixed, not because it is slow, but because it would be 'cleaner' to be refactored, then you will likely be rightfully fired for a poor judgement call.

      --
      XML is like violence. If it doesn't solve the problem, use more.
    3. Re:Doesn't always help. by phantomfive · · Score: 1

      The story that really drove this point home for me was about a text editor that worked perfectly.......except if you tried to save when your file was exactly 2^16 bytes long. Any longer, it was fine. Any shorter, it was also fine.
      The book that related this story then went on to calculate how many combinations of tests you would need to run before testing every possibility in a reasonable sized program. A ridiculous amount.....

      --
      "First they came for the slanderers and i said nothing."
  72. example is trivially simple by Chirs · · Score: 1

    Now do the nested version when you're trying to allocate multiple resources independently and need to clean up all of them if any of them fail. Oh, and it needs to fit within 80 columns due to other coding rules.

    Gotos are a clean way of doing error handling.

  73. handy for debugging by Chirs · · Score: 1

    The "single point of exit" can make some types of debugging easier since you can hook the exit with less work.

  74. 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
  75. Not taking into account portability in C by Anonymous Coward · · Score: 0

    I do this often when in a hurry or when I'm pretty sure the code is only going to run on the intended platform (always embedded mcu), when for instance a data frame is received with the same endianness as the platform i can extract a word like *(uint16_t *)pBuf instead of doing it with shifts and addition. Stuff like that.

  76. I *never* break out of loops ... by Qbertino · · Score: 1

    I never break out of loops or ifs with a direct return.
    It somehow makes me cringe in a very uncomfortable way.
    I always return one level up, even if it means using a utility variable (often called returnMe and initialised at the beginning of a function).

    I couldn't say that that is much better, but it does make me *feel* a lot better.

    As for more good habits:
    I've recently gotten into more serious function programming territory, trying to avoid variables entirely. Doesn't always work and gets your head all in a knot, but you learn a lot. And it is faster - both in coding and at runtime.

    --
    We suffer more in our imagination than in reality. - Seneca
  77. I hate good programming just as much by Anonymous Coward · · Score: 0

    Beautifully crafted over-engineered OO spaghetti featured dozens of widely over-documented classes that feature every theory the coder learned at school bolted onto a time saving framework that another artisan wrote to prove something.

    And not a single spec doc so nobody knows WTF it is supposed to do.

  78. Let me show you by Anonymous Coward · · Score: 0

    int main() {
            unsigned int bullet=1;
            headshot();
            headshot();
            bullet--;
            return 0;
    }

    Now you have.

  79. Best way to get rid of a bad rule? by Anonymous Coward · · Score: 0

    The best way to get a bad law repealed is to enforce it strictly - Abraham Lincoln

  80. Size it based on analysis, not ritual by Tablizer · · Score: 1

    "Coupling" is a vague concept, I have found out. Specific "types" of coupling could be called code patterns, but coupling as a general concept is vague (as currently described by authors).

    As far as function/method size, in my opinion "it depends". If it's quite short or quite long, at least pause to ask "why" and consider alternatives. But don't force every one to be 20 lines out of some ritual habit.

    My "best" shorter methods tend to be called many times. They often consolidate commonly-found domain idioms into a simpler concept.

  81. Pay Now or Later by __aanhjr1420 · · Score: 1

    "We've thumbed our nose at the rules of good programming, typed out code that is totally bad -- and we've lived. There were no lightning bolts from the programming gods. Our desktops didn’t explode. In fact, our code compiled and shipped, and the customers seemed happy enough."

    No, but breaking programming rules doesn't cause a problem today. It causes one tomorrow. It's akin to gluing a loose electric plug to the outlet. It solves the problem (very well!), but when you later need to unplug the TV, it's going to be needlessly difficult.

  82. I feel your anonymous pain, AC by Phil+Urich · · Score: 1

    If the unit of work provided by a function changes, then a programmer who understands what maintenance is like will also update the comment describing what it does.

    My goodness, people! How hard is it to declare what something does? Get off my lawn!

    Working at a software development firm where the programmers are almost all folks with engineering degrees, I not only feel your pain, but experience it nearly-daily. We'll have cases in our bugtracker that say "fix {programname}", then the commit will say "fixed" and the case will be marked closed without going to anyone for testing. Then I'll run into a bug that traces back to that commit.

    I rebel by being extremely verbose in commit messages and emails and such whenever the fancy strikes me, and when the engineers get upset I just retort that I'm averaging things the fuck out to what they should be!

    The funniest part is when they complain about some since-departed programmer's code being so mysterious and unreadable and hard to figure out why it was written the way it was. If only they had documented it, you say? Sigh.

    --
    I remember sigs. Oh, a simpler time!
  83. Too many requirements by burbilog · · Score: 1

    Pick any two at once

    1. Re:Too many requirements by phantomfive · · Score: 1

      Not likely.
      If the code is not readable, it's probably not going to be flexible.
      If it is readable, then any bugs will be fixed quickly.

      --
      "First they came for the slanderers and i said nothing."
  84. Issue with java programming in python. by Anonymous Coward · · Score: 0

    The "standard" OO rule you talk about is a kludge due to learning OO in languages like Java. In Java it's impossible to control or intercept access to an attribute, so once the cat's out of the bag, you need to wrap each such access in an explicit getter/setter.

    Attribute access (obj.attribute = 1) is more elegant and easier to read, and is actually consistent with other OO encapsulation practices like "obj1 + obj2" is easier to read than obj1.add(obj2). In Java, once the client uses the attribute, you're blocked from doing anything more advanced with it. In Python, that's no problem - descriptors/properties are specifically designed to intercept attribute access and the caller doesn't need to change anything, so obj.attribute will call an instance getter method if you want it to.

    The current crop of Java programmers who write Java in Python go on to generate getters and setters and abstract classes and other Java idioms, resulting in ugly unmanageable code that exemplifies the very worst of both worlds.

    1. Re: Issue with java programming in python. by silentcoder · · Score: 1

      I have seen some code like that. Pray you never need to maintain python written by a java coder.

      --
      Unicode killed the ASCII-art *