Slashdot Mirror


Defining Useful Coding Practices?

markmcb writes "A NASA engineer recently wrote about his disappointment that despite having well-documented coding practices, 'clever' solutions still made the code he has to maintain hard to follow. This got me thinking about the overhead spent at my own company regarding our code. We too have best practices that are documented, but most seem to focus on the basics, e.g., comments, modularity, etc. While those things are good, they don't directly ensure that quality, maintainable code is written. As the author points out, an elegant one-liner coupled with a comment from a few revisions ago makes for a good headache. I'm curious what experience others have had with this, and if you've seen manageable practices that ultimately offer a lot of value to the next programmer down the line who will have to maintain the code."

477 comments

  1. Simple... by Anonymous Coward · · Score: 5, Insightful

    Simple, clever doesn't pay the bills, reliable and maintainable do. It's a cost benefit analysis: if that clever one-liner saves many man-hours of work, then probably a good idea. If it saves you two or three lines of code and all of an addition 45 seconds, probably not worth the blow to maintainability and readability. It's always a tradeoff...just have to decide which is more important in any given context, and at most companies, reliability and maintainability is king compared to a slight runtime increase or 45 seconds/3 lines shaved off.

    1. Re:Simple... by Coryoth · · Score: 4, Insightful

      Simple, clever doesn't pay the bills, reliable and maintainable do. It's a cost benefit analysis: if that clever one-liner saves many man-hours of work, then probably a good idea. If it saves you two or three lines of code and all of an addition 45 seconds, probably not worth the blow to maintainability and readability.

      I view it as a premature optimization issue. It's very rare indeed that you save much time in writing code by doing something cute or clever; usually it's a matter of trying to do something slickly to save cpu time or memory. Rather than prematurely optimize I find it is best to try and write things in the most clear straightforward fashion first (even if it's not the most efficient implementation) and then go back later and make things more efficient if it proves to be necessary (often it doesn't because of real bottlenecks elsewhere).

    2. Re:Simple... by Z00L00K · · Score: 1

      There is clever and there is clever.

      You may have a clever detail in the code, and you may have a clever overall structure.

      And in a larger solution there will always be parts that are clever and parts that are stupid. Sometimes by the same programmer.

      And appeared to be a good idea at the time may end up being an outrageously stupid idea when time has passed and the component has grown over all limits.

      It's also important to notice that an idea can be excellent from the point of understanding of the solution but have absolutely horrible performance. And it can be the opposite too, excellent performance but you have to be top grade to understand how it works.

      The thing is to find a fine balance between structure and performance.

      And as a designer - don't confuse people unnecessarily by using "smart" coding by utilizing "stored procedures" in external resources like databases. That will ultimately just cause headache. People may reason that using stored procedures will decouple the database from the code, but it also adds a new layer of code which is requiring different skills to maintain and that is tricky to debug in addition to not providing compile-time warnings/errors when there is a mismatch.

      --
      If builders built buildings the way programmers wrote programs, then the first woodpecker would destroy civilization.
    3. Re:Simple... by camperdave · · Score: 2, Interesting

      The thing is, though, that that sort of programming used to fetch the highest dollar. This was back in the days when computers only had 2K of memory and you had to use overlay programming. 45 seconds is always a significant amount of time.

      I remember porting a piece of date validation code from an old WANG computer. At the heart of the algorithm was the computation 3113-1881 (or something like that). I ported everything straight over, and... it didn't work. I ran through the code manually, and... it made no sense. 3113-1881 is 1232. I went back to the WANG computer and typed in PRINT 3112-1881, and suddenly the algorithm became clear. On the WANG, 3113-1881 was 1231.9999, which made a perfect mask for a numeric date.

      --
      When our name is on the back of your car, we're behind you all the way!
    4. Re:Simple... by b4dc0d3r · · Score: 1

      What people forget, every single time, is that people are different. Coding practices differ depending on your language, and your coding team's abilities.

      I saw lots of code during peer review that was just terrible - looping to fill a DataTable from a DataReader, applying transformations for a single column. My code would have applied a function to the Template, so you let the Template iterate and call your function for the translation.

      ASP.NET does not make it easy to do such things, and there are so many ways to do it, and so many code examples which recommend one way and some recommend another. And the documentation is terse - it does not explain what's happening.

      Do you expect me to use Reflector to figure out how the language works when I have a line item due Monday? No, then I will do a code search, copy and paste, and when I find a different solution I'll have two different methods in the code, cos I'm not going to back-port anything that works and has been tested.

      Ultimately, you need to agree on something that is readable by everyone who might read it (including support staff if applicable). If looping for data transformations is more clear, go with that. I decided to bite my tongue and allow code like that if there existed an example of its usage (without being a recommendation against using it of course). It is more clear that way, but lots of overhead. So you need to have a body of coders who understand the language completely and know which design patterns to choose.

      Do you fill an ALLOW list of properties from an initialized array so that someone can't just go around changing it, or load it from a config file so someone can just go around changing it? Do your array functions check the lower and upper bound, or just go from 0 to <= .Length?

      My point, if I have one, is to choose an appropriate language, and make sure your people know how to use it. Then they will code appropriately and it will be understandable. Any time you move to a different language, or a different version of the same language, there's a learning curve and the first code out the door will have problems. Do you rewrite it later? Or do you invest time up front to understand the language features and *recommended* usage? I'm saying spend the time up front. You're not being paid to learn the language as you go - you're being paid to know it. And if the job requirements change, management has to give you time to make sur eyou know the new stuff, so you can do your ACTUAL job, which is to create readable output.

    5. Re:Simple... by digitig · · Score: 1

      Simple, clever doesn't pay the bills, reliable and maintainable do.

      Whose bills? You're right that reliable and maintainable pay the shareholders' bills, but there's no difference to the coder's bills (because [s]he's off on a new contract with a different company by the time the maintenance problem hits) unless you have really good review processes in place. So the coder is going to do it the way that gives most satisfaction, not necessarily the way that's best. I reckon that strong reviews are the only way to overcome that.

      --
      Quidnam Latine loqui modo coepi?
    6. Re:Simple... by dougisfunny · · Score: 1

      While it may not be "smart" coding utilizing "stored procedures" just for the sake of decoupling the database, it is smart when there is a call for complicated set logic which is much more efficient done in a stored procedure.

      --
      This is not the funny you're looking for.
    7. Re:Simple... by Anonymous Coward · · Score: 1, Interesting

      Simple, clever doesn't pay the bills, reliable and maintainable do. It's a cost benefit analysis: if that clever one-liner saves many man-hours of work, then probably a good idea. If it saves you two or three lines of code and all of an addition 45 seconds, probably not worth the blow to maintainability and readability.

      I view it as a premature optimization issue. It's very rare indeed that you save much time in writing code by doing something cute or clever; usually it's a matter of trying to do something slickly to save cpu time or memory. Rather than prematurely optimize I find it is best to try and write things in the most clear straightforward fashion first (even if it's not the most efficient implementation) and then go back later and make things more efficient if it proves to be necessary (often it doesn't because of real bottlenecks elsewhere).

      And the funny thing is, absent real in-depth instruction-by-instruction profiling output from real production inputs on real production hardware, any "clever optimizations" introduced are just as like to slow things down as they are to speed things up.

      I've found that out the hard way. Many times.

    8. Re:Simple... by ickpoo · · Score: 1

      Stored Procedure do just the opposite, if you are using stored procedures then your application is in the database as well as using it. It is more tightly bound to the database then before. That said, there are times when using stored procedures is the best solution - speed, clarity come to mind.

      --
      I am not a script! .Sig?
    9. Re:Simple... by MrBigInThePants · · Score: 1

      While I agree with the sentiment, the problem is harder than this to solve.

      As soon as you try and define and write done said standards that will cover each and every case in a meaningful way you have pages of bureaucratic nonsense that few developers will remember or try to stick to.

      Standards are better "enforced" coercively via peer review etc. If you are not doing peer review, you really should be.
      Of course this practice requires a level of discipline also, just not as much.

      There are many ways to write readable and maintainable code and this can change based on the type of code you are writing as well as the language.

    10. Re:Simple... by Madsy · · Score: 1

      It's not always as clear-cut as this. Some code simply *is* complex by nature, or needs to be complex to meet certain requirements, like high performance. A real-life example could be finding the type of an instructions in a RISC instruction set where all the instructions is of the same fixed length. The 'clean' solution be something like:

      int ParseInstruction(unsigned int instr)
      {
          int i;
          unsigned int sbo,sbz;

          for(i=0; i<NUM_INSTR; ++i){
              sbo =instr_set_mask[i]; /* instruction set bit mask */
              sbz = instr_zero_mask[i]; /* instruction mask for required zero bits */
              if((instr & sbo) == sbo && (~instr & sbz) == sbz)
                  return i;
          }
          return InstrUndefined;
      }

      Elegant, readable and very maintainable, but yet horribly slow for most solutions. Instead you end up with a nightmare of branches in order to avoid scanning through the whole instruction set for every instruction.  My point is that in practice, there is no way you can always make super maintainable code *and* fulfill all the requirements. Some solutions are butt ugly while still being the best one for the current problem. Heck, some of the easiest algorithms to read are the ones with the highest run time. For example long multiplication vs Toom Cook multiplication.
      Premature optimization is evil though, and I agree with the rest of your post. I just think it came off as a bit purist.

    11. Re:Simple... by IkeTo · · Score: 1

      Hmm... if the instruction set structure is really such that I cannot make out a sufficiently small table and register the prefixes of instructions into it, I'll write a nice code generator to generate the "nightmare of branches" and then forget about it. I hate to maintain crap... the instruction set is going to change at exactly the day when you forget how the branches work!

    12. Re:Simple... by hesaigo999ca · · Score: 1

      I agree to a certain point, I find sometimes the reverse is true also, when you have multiple pages of code because everybody is either tab happy, or thinks that because you have a line of code that extends a bit too far, that it should be written on 2 or 3 lines to make it readable, I don't agree.

      I have seen some code that (especially using the new regions with m$ vs2005), we have an easier time
      maintaining code, by far, by making more one liners then would be the norm...
      example
      dim obj as ttt.ddd.walmart.component = _
                    new ttt.ddd.walmart.component(id,code)
      obj.SetLocation(storeFront,branch,division)
      obj.BuyItem(product, _
                                          price,_
                                          qte,_
                                          rebate,_
                                          branch,_
                                          divison,storefront,etc,etc,etc)

      we put this instead
      dim obj as ttt.ddd.walmart.component = new ttt.ddd.walmart.component(id,code)
      obj.SetLocation(storeFront,branch,division)
      obj.BuyItem(product,price,qte,rebate,branch,divison,storefront,etc,etc,etc)

      Because, when talking about parameters, usually breakpointing into the function lets you see what your params are anyways, so we do not bother tagging that line, instead tagging the line inside the function to break on.
      when you read ours, its simple to read, when you try to read the usual 20 lines for 1 function call, it gets tedious fast!

      I was called the one liner man for a long time, and toned it down, but did end up showing the effectiveness of one lining when you can, you spend less time scrolling up and down and side ways and makes the code more readable
      when you don't worry too much about the params, but more about the movement/point in code.

      All in all, it all stems from where the person works if they are close minded, and do not want to change with the times, or open minded and willing to listen to all their employees to bring about new , more effective ways to code.

  2. multiple revision? by leuk_he · · Score: 2, Insightful

    As the author points out, an elegant one-liner coupled with a comment from a few revisions ago makes for a good headache.

    A oneline that had multiple revision should be completely rewritten, because if you manage to get multiple changes in one line it surely is a mess... somwhere.

    1. Re:multiple revision? by joaommp · · Score: 1

      At my company, the coding standards include not only guidelines for styling and comments, but also for performance optimization, code run-time stability and robustness, tips to avoid common programming errors, tips about readability, safety, security and productivity.
      The manual has a whole chapter dedicated to the compromises between performance, productivity, readability, robustness and safety.
      There's also a summarized presentation version of the manual that all new employees must attend before they're allowed to begin coding for the company.

    2. Re:multiple revision? by daedae · · Score: 2, Informative

      Unless of course they meant a one-liner coupled with a comment from the previous implementation, ie, the clever programmer failed to cleverly update the comment.

    3. Re:multiple revision? by Anonymous Coward · · Score: 0

      I read "a few revisions ago" as meaning that the source file has been committed multiple times since then, not necessarily with changes to the "elegant" one-liner.

      Who reviewed this story lead, anyway? Kids these days would never have made it in the good ol' comp.os.vms ng.

    4. Re:multiple revision? by Toonol · · Score: 2, Insightful

      A oneline that had multiple revision should be completely rewritten, because if you manage to get multiple changes in one line it surely is a mess... somwhere.

      That makes me think of comparisons to sentence and paragraph structure. A sentence should enough words to express one thought, a paragraph enough sentences to express one idea. There are legitimate reasons to vary from those requirements at times, but in general it will improve your writing to adhere to those concepts. A lot of unreadable prose is generated by people that don't understand the function of paragraphs.

      An obvious analog is lines of code and function blocks. I write what many of you would probably consider verbose code, because I prefer a line of code to always do just one thing. I'll increment x on one line and set y=x on another line, if those are (in an abstract sense) two unrelated operations. It feels conceptually cleaner to me to keep each logical step separate.

      A one-liner seems to me to be reminiscent of one of those eighty-word sentences that you will read in a EULA... that are grammatically correct, legally precise, meticulously crafted, performs their function well, and yet is unreadable by a normal human. The lawyer that writes a sentence like that probably feels the same sense of pride that a programmer feels when they replace a twelve-line function with one clever one-liner.

    5. Re:multiple revision? by Yetihehe · · Score: 1

      A sentence should enough words to express one thought, a paragraph enough sentences to express one idea.

      I think you the whole idea.

      --
      Extreme Programming - Redundant Array of Inexpensive Developers
    6. Re:multiple revision? by jellyfrog · · Score: 1

      Accidentally or deliberately?

  3. Literate Programming by John_Sauter · · Score: 3, Insightful

    To my mind, the best coding standard is Don Knuth's Literate Programming: http://www.literateprogramming.com/. Quoting:

    I believe that the time is ripe for significantly better documentation of programs, and that we can best achieve this by considering programs to be works of literature. Hence, my title: "Literate Programming."

    Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

    The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding, using a mixture of formal and informal methods that reinforce each other.

    1. Re:Literate Programming by CortoMaltese · · Score: 3, Insightful
      Yup. I'd go as far as saying readability is more important than correctness; fixing or improving easy to understand programs is trivial compared to trying to decipher spaghetti code. You write code for other people, and that other people might be you a few years from now.

      I'm afraid you can't really force this attitude on people by using coding standards etc. though. I think it's something every coder needs to figure out for themselves. Like Pragmatic Programmer says, "care about your craft".

    2. Re:Literate Programming by Anonymous Coward · · Score: 0

      Yes, I use a similar way of thinking.
      I couple this way of thinking about source code (meant for humans to read even before computers) with personal face to face exchange of information, especially when handing over maintenance of a codebase to someone else.

    3. Re:Literate Programming by joaommp · · Score: 3, Insightful

      Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

      I'm sorry, but I can't help but disagree with this sentence. The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do.
      Computers don't do what we want, they do what we tell them to do. Success in programming a computer comes from telling it what we want it to do.
      One must not compromise the precision of the orders it gives to the computer in order to achieve readability by something/someone else than the computer. One should, however, try to make his code as readable and elegant as he possibly can without sacrificing precision in the message to the computer.
      If we program without prioritizing the computer, we may end up writing something that may look, to us and anyone else that reads it, like what we want the computer to do, but the computer my not take it that well...
      I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much.

    4. Re:Literate Programming by joaommp · · Score: 1

      typo, correction

      "I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should NOT allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much."

    5. Re:Literate Programming by UnxMully · · Score: 1

      Yup. I'd go as far as saying readability is more important than correctness; fixing or improving easy to understand programs is trivial compared to trying to decipher spaghetti code. You write code for other people, and that other people might be you a few years from now.

      Can I hold out for testable as well as readable? Tthe efficiency and quality gains you make from being able to run a suite of unit tests that confirm that the code still works as intended, or as you intend it to when you change it, shouldn't be underestimated.

    6. Re:Literate Programming by John_Sauter · · Score: 3, Insightful

      I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should NOT allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much.

      I think you are misconstruing the intent of Literate Programming. It isn't Programming if you aren't telling the computer what to do. Programming becomes Literate Programming when a person, reading your code, is also able to understand what you are telling the computer to do.

      The first time I read a program, I ignore the code and look only at the comments. I hope to get a high-level understanding, so on the second read I can comprehend the details better. When I review my own code I do the same, and improve the comments if they don't convey an appropriate level of information.

    7. Re:Literate Programming by joaommp · · Score: 1

      I'm not challenging whether one tells the computer what to do or not. I'm challenging whether or not one tells the computer what he wants it to do. You can tell a computer to do something else than what you want it to do. It's easy... just do it wrong. And I'm just essaying on that sentence alone. I have not read the book, so that sentence is what I'm left with and is that sentence I'm deconstructing.

    8. Re:Literate Programming by ClosedSource · · Score: 1

      "I'd go as far as saying readability is more important than correctness;"

      This reminds me of the joke in the "My Fair Lady": "The French don't care what they do actually
            As long as they pronounce it properly"

    9. Re:Literate Programming by lophophore · · Score: 5, Insightful

      Many years ago, a very smart man explained to me that my customer is not the compiler. My customer is the next poor slob who has to work on the source code. Software maintenance is a fact of life. Someday, somebody is going to need to read and understand what is in your code.

      Ignore maintainability at your peril. If people on my team ignore maintainability, they become unemployed.

      Do you even know who Donald Knuth is? I'll take his advice over yours, any day.

      --
      there are 3 kinds of people:
      * those who can count
      * those who can't
    10. Re:Literate Programming by Alomex · · Score: 2, Insightful

      The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do.

      This is a very common misconception, we do want other humans to know what we want the computer to do, namely the poor saps who end up maintaining your crappy code.

      So if you think about it, there are two consumers of code: the compiler and the fellow who will maintain it for the next ten years. If you program with just one or the other in mind you are doing a darn poor job at writing code.

      One should, however, try to make his code as readable and elegant as he possibly can without sacrificing precision in the message to the computer.

      The computer doesn't complain if it has to work twice as hard to properly parse your code. So in the tradeoff between human and computer readability we must favor the human. Of course if we end up with incorrect code in the name of readability we have gone too far. I have yet to see code like this.

    11. Re:Literate Programming by joaommp · · Score: 1

      Well, if you say that, then you misunderstood me. Yes, I know who he is. I never said to ignore maintainability. Please, read carefully what I wrote.
      And your client, is neither the compiler nor the "next poor slob who has to work on the source code". The client is the guy that will buy your software and expects it to behave according to what it says it does.

    12. Re:Literate Programming by Anonymous Coward · · Score: 0

      I'm not challenging whether one tells the computer what to do or not. I'm challenging whether or not one tells the computer what he wants it to do. You can tell a computer to do something else than what you want it to do. It's easy... just do it wrong. And I'm just essaying on that sentence alone. I have not read the book, so that sentence is what I'm left with and is that sentence I'm deconstructing.

      I believe Knuth's intent involves a change in priorities, but not a change in the requirement that the computer is given correct instructions. There is no conflict between correct computer instructions and readable code, since comments can be used to augment readability without impacting the instructions to the computer.

    13. Re:Literate Programming by Anonymous Coward · · Score: 0

      Have you ever read a mathematics paper? Typically, there will be big blocks of text (with symbols interspersed), and then formulae or equations in floating blocks. The idea is that you explain and define your terms in the blocks of text, and define your functions and relationships in the "blocks" of "math". (Mathematical papers are a bit more involved than this. You can have mathematical "blocks" in your text, as long as any sentence that contains a symbol is a proposition, and the symbol isn't a free variable, in context. Literate programming systems don't typically do this kind of "inline" definition")

      As it happens, every programming language is a constructive proof system, and vice-versa. Every computer program is a constructive mathematical proof. If you structure your program in a "literate" way, this connection becomes much more apparent. You will automatically have to structure your code as if it was an argument. This makes it significantly easier to validate the code. (It is also helpful to have some higher order constructs, like easy to use functors)

      You can truly have mathematical rigor in your code. You just have to approach your code writing as proof writing. Typically, this isn't worth the effort for most problems. I only do it for the "tricky" algebraic (algorithmic?) libraries in my code. Not for my data or control libraries. Where the algorithms are domain specific and potentially non-obvious. My data libraries (the libraries that contain instances of my data types) don't really need any comments. Every instance is going to be in a normal form, in virtue of my coding conventions (well, this also happens to be enforced by my current language of choice, but I always did that automatically anyway). The control libraries are obvious enough if you use sensible names.

      It's hard to tell what an OO programmer might think of all this. The "factory" pattern is a "simple" implementation of a functor for OO. How many classes do you have to write? Want to see how to construct a functor in Haskell? collection `fmap` f, where f is a function of the appropriate type. (The backticks turn a function into an infix operator)

      So what is the point of all this? Well, the algebraic libraries are where all the effort should go. Precisely because they are the tricky ones. But it is better to keep all of that complexity together, than strewn throughout a codebase. Another point is that this architecture and methodology enforces normal forms for every value. In particular, this means that even enormous refactoring can be done mechanically. You should expect that any change to a data type will change the "shape" of its values. This is inescapable, even in OO. But you can't easily write regular expressions to parse an OO language and apply trivial syntactical transformations. You can do that in a language where every value can look almost like a CSV list.

    14. Re:Literate Programming by CAOgdin · · Score: 1

      Perhaps you've forgotten: Computers are here to serve human beings, not the other way 'round.

      There is a fundamental lack of engineering principles in programming, which leads to a lot of lousy programs. When I apply good engineering practice to software design, it always turns out better in the end, especially when you realize that you're not writing "A" program, but the first of a series of ever-changing (hopefully "ever-improving"( programs, which we identify as "versions." Even tiny scripts of mine have gone through many iterations as I discover conditions under which they don't perform, or I discover a new capability that has become important, now that users (and I) have gained experience with the original.

      Until programmers realize they must have a DISCIPLINED approach, we'll contine to implement software that is evolved through the finding of bugs, instead of focusing on getting it right the first time.

    15. Re:Literate Programming by joaommp · · Score: 1

      You should pay better attention to what I wrote. As I've already explained twice before... I am NOT discarding readability. Neither I'm advocating we shouldn't give a bit more work to the compiler. I'm advocating that if you're supposed to write a program that does X, you should write a program that does X and, yes, have care when writing it so that it is maintainable. But you should NOT write a program that does approximately X for the sake of a somehow mythical perfect maintainability. Have your program do X and make your best at making it maintainable. It's easy do make a program that does exactly what you want and still it's maintainable. FOR MOST, it's just a question of not being lazy and do the job right. For some others, a bit more learning, practice and training. And for a lot other, stopping the "heroics" and "macho dev" complex.

    16. Re:Literate Programming by joaommp · · Score: 1

      For the last time, if anyone really bothered to read carefully what I said, they would know that it is exactly what I was talking about: discipline. You all seem so willing to find a point of disagreement that you fail to really see what I'm talking about... but, well, this is slashdot, anyway...

    17. Re:Literate Programming by joaommp · · Score: 1

      Perhaps you've forgotten: Computers are here to serve human beings, not the other way 'round.

      And yes, this is true. And that's exactly why what I said applies. Because if they're supposed to serve us, than we better know how to tell them what we want. They're not psychics to guess it for us.

      If you're the keeper and you want your minions to bring you a coke, will you tell them to bring you a drink and expect them to know it's coke?

    18. Re:Literate Programming by joaommp · · Score: 1

      I'm not analyzing Knuth's intentions, just the dangers of that sentence alone. There is no conflict if one does the job right. However, code readability is not only about comments or styling. And sometimes, a little change to improve readability with another construct, even if that construct, most of the times is perfectly equivalent, can have a huge impact on the outcome of the project. As I said, I don't want to sacrifice readability or maintainability, but I want even less to sacrifice the accuracy of the result.

    19. Re:Literate Programming by SanityInAnarchy · · Score: 1

      Tthe efficiency and quality gains you make from being able to run a suite of unit tests that confirm that the code still works as intended,

      This.

      I would take it a step farther -- first, code like a girl. Then, use behavior-driven design. A comment explaining how the code works is well and good, but a human-readable spec which explains what it's supposed to do is, IMO, the best possible example you can provide.

      Well-written specs don't really even need comments, if you provide descriptive names -- though that's not an excuse for leaving the original code uncommented.

      --
      Don't thank God, thank a doctor!
    20. Re:Literate Programming by Anonymous Coward · · Score: 0

      "The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do."

      Fail. Programs aren't written to amuse computers. They are written to serve people. If you cannot clearly explain to people what you are doing, you almost certainly won't do it right. One of the people you need to be explaining it to is yourself. This is the essence of Literate Programming. Write the comments, so you'll clearly relate what the functionality is. Write the code so that the implementation matches the described function.

      Too often I hear the excuse that code shouldn't be commented because comments swiftly become obsolete. I don't accept that. If there isn't enough time in the budget to allow for a COMPLETE maintenance of the comments and then the code, then the software is likely to rot as it builds up a legacy of instructions whose full impact are not well understood.

    21. Re:Literate Programming by szetlan · · Score: 1

      Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

      I'm sorry, but I can't help but disagree with this sentence. The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do. Computers don't do what we want, they do what we tell them to do. Success in programming a computer comes from telling it what we want it to do.

      Note quite right. The purpose of creating a computer program is to get work done. This includes, but is not limited to, telling the computer what to do. We want to maximize the amount of work done by the computer and minimize the work done by people. This implies striking the right balance between optimizing the run-time of the program and optimizing BOTH the readability AND usability of the program. When modifying a program, we have to balance effectiveness, readability, and usability. Comparing the potential benefit of a faster-running program with the cost of poor readability or usability is difficult, but (at least in business) can be done by converting all units to dollars. Dollars are then easily convertible to pizza and beer, units of measurement familiar to nearly every programmer in the world. In some cases, cryptic one-liners that shave a few milliseconds off the per-cycle run-time produce many millions of pizzas and thousands of gallons of beer annually, at the expense of a few pies and a six-pack in maintenance per year. Who cares if that code is hard to read? We have PIZZA and BEER! But saving a slice and a half-pint at the expense of an office pizza party .... that's just a travesty. And don't get me started on all that pre-packaged stuff that costs nothing to install, runs really fast, and is super-maintainable -- but that costs the end-user all of Papa John's and most of Sam Adams just to make a few photocopies. Feh.

    22. Re:Literate Programming by noidentity · · Score: 1
      A program is simply a precise specification of exactly what we want done. The reason we have to give so many details is that there are that many degrees of freedom. Even if we write up a requirements document, it still leaves details out; it's not some deficiency of the programming language that we have to specify details.

      We always have flexibility in exactly what is done that will still meet our needs, for example I don't care whether the file is copied 512 bytes at a time or 32768 bytes at a time, or what the variable names in the source code are. Within this flexibility we can choose a way of doing things that makes the program easy for a human to make sense of as well.

      And then there are comments, not executable and thus not testable. They should represent things that can't be tested or don't need to be, like the reasons for doing something a particular way.

    23. Re:Literate Programming by nidarus · · Score: 1

      One must not compromise the precision of the orders it gives to the computer in order to achieve readability by something/someone else than the computer.

      Every time you use a programming language, as opposed to assembly or straight machine code, you're doing just that.

    24. Re:Literate Programming by joaommp · · Score: 1

      ok, you people, really need to be pay way more attention to what I write...

    25. Re:Literate Programming by haruharaharu · · Score: 1

      I'm sorry, but I can't help but disagree with this sentence. The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do.

      I hope I never have to read your code.

      --
      Reboot macht Frei.
    26. Re:Literate Programming by nidarus · · Score: 1

      For the last time, if anyone really bothered to read carefully what I said, they would know that it is exactly what I was talking about: discipline. You all seem so willing to find a point of disagreement that you fail to really see what I'm talking about... but, well, this is slashdot, anyway...

      Two options:

      1. Everyone who chose to reply to your comment (or, as you seem to imply, everyone on slashdot) is an idiot.
      2. You couldn't effectively convey your message. Knowing what you meant, and having other people understand it are different things.

      I've read your original comment, and in my opinion, it's option #2. Which is kinda ironic, considering what you've said there.

    27. Re:Literate Programming by joaommp · · Score: 1

      I didn't say people were idiots. only that they're so used to read things fast and without really paying attention. We here have an expression for that, which roughly translates to "reading in diagonal". And if you say it's ironic, that means you did understand my message, at which point it implies you're creating a paradox, because if I didn't convey my message right, you would not have understood it.

    28. Re:Literate Programming by joaommp · · Score: 1

      I can give you examples of my code, if you wish. From the opinions of everyone that works it me, it is readable and maintainable, without compromising performance, functionality or accuracy.

    29. Re:Literate Programming by Anonymous Coward · · Score: 0

      I'm sorry, but I can't help but disagree with this sentence. The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do.

      80% of the cost of software is maintenance.

      Computers don't do what we want, they do what we tell them to do. Success in programming a computer comes from telling it what we want it to do.

      True... if you never have to maintain your code and you are the only person working on it.

      One must not compromise the precision of the orders it gives to the computer in order to achieve readability by something/someone else than the computer.

      Totally disagree with you. ALL code is precise. The computer doesn't care if it is clever or clear, people do. So Clear is always better.

      If we program without prioritizing the computer, we may end up writing something that may look, to us and anyone else that reads it, like what we want the computer to do, but the computer my not take it that well...

      See above. The computer doesnt care if the directions are clever or clear. It just does what you tell it.

    30. Re:Literate Programming by joaommp · · Score: 1

      No, the code isn't precise, if you incorrectly input the wrong code into the computer, under false assumptions of perfect match of results between the code that you do know does the trick and the code you wrongly believe does the trick but that you are using instead because it seems more readable. You could probably have a better understanding of what I meant if you read the other comments in this discussion...

    31. Re:Literate Programming by coryking · · Score: 1

      only that they're so used to read things fast and without really paying attention.

      You can't expect people to change their reading style just to figure out what the hell your slashdot post means. Basically, you are saying that your post and its content is so important that everybody else must drop everything and change their entire behaviour for you. In fact, not only must they change their bevahour to what *you* think is right, but they are idiots because they haven't already You might not think what I just wrote it true, but your statement implies it.

      Good writing is all about being humble and putting yourself in the readers shoes. Your reader is busy and has many other things going on. This is true here on slashdot where this is all done for shits and grins but it is even more true in real life.

      Knowledge is power. If you can clearly communicate what you mean, that puts you much further ahead than somebody know knows more than you but cannot communicate well.

    32. Re:Literate Programming by haruharaharu · · Score: 1

      sounds like your first priority is making the job of the guy after you easier, but you just don't want to admit it :)

      --
      Reboot macht Frei.
    33. Re:Literate Programming by Gouru · · Score: 1

      Cobol is NOT conducive to literate programming. Yes, it uses 'english' names for common operations, but this is not what makes a program 'literate'. The data division with it's cryptic layout, level numbers to specify subdivisions, Sections with differing rules and syntax do not lead to literate programming.

      The Procedure division allows for english-like statement "Move a to b." instead of "b=a;", however neither of these statements are any better at explaining to a human what we want a computer to do. It can be argued that Cobol is more clear to an English speaking non-programmer, a subset of 'human beings', and generally not the target audience of a computer program. It can also be argued that "b=a;" has more universal understanding among the subset of 'human beings' called 'developers' that make up the target audience.

      I started with COBOL, I wrote COBOL code for many years (started programming in 68), and I can assure you, Knuth is NOT referring to language semantics in his statements.

    34. Re:Literate Programming by Anonymous Coward · · Score: 0

      Actually, my job is to make my client happy with the results, but I do occasionally remember someone else may have to touch that code... 8-)

    35. Re:Literate Programming by joaommp · · Score: 1

      No, I'm not saying people have to change anything. You're just assuming things I never said and you're just one more person accusing me of doing something I didn't do. None of what I said implies any of what you just accused me of.

      Don't expect me to agree with comments that were made based on lack of comprehension, be it my fault or not.

      Good writing is about being humble, but the same applies to writing good comments to anyone else's comments.

      Giving the other face doesn't really work.

      Let's assume people don't really pay attention to my comments. And they comment something that shows just as much.
      Are you expecting me to just suck it up? They don't have time to read, but they have time to comment (sometimes very negatively in a non-constructive way)...
      If someone wants to comment on someone else, they should at least pay attention to what that someone else really wrote first. And, once again, this, of course, assuming, it's not my bad writing.

      I never said my post and my content is so important everyone else should just drop everything and change their entire behavior for me. No, that's you saying. I only said that if someone wants to criticize, at least they should know what they really are criticizing, instead of just getting half of an idea and immediately ranting about it.

    36. Re:Literate Programming by coryking · · Score: 1

      I never said my post and my content is so important everyone else should just drop everything and change their entire behavior for me

      It is implicit in your writing and frustration that nobody understands what the hell you are talking about. If "If someone wants to comment on someone else, they should at least pay attention to what that someone else really wrote first" isn't expecting people to change their behavior for you, I don't know what is.

      They don't have time to read, but they have time to comment (sometimes very negatively in a non-constructive way)...

      Welcome to Slashdot and every web form in existence :-)

      PS: Pretty much my entire last comment can apply to coding as well. Well, kinda sorta.

    37. Re:Literate Programming by joaommp · · Score: 1

      Reading carefully the piece they want to comment, is not a question of changing behavior, is a question of respect. How would you like if it was you? How would you like if you were condemned to jail without an investigation?

    38. Re:Literate Programming by Anonymous Coward · · Score: 0

      The client is the guy that will buy your software and expects it to behave according to what it says it does.

      Without a doubt the vast majority of code written is for internal use, not sold.

    39. Re:Literate Programming by coryking · · Score: 1

      Reading carefully the piece they want to comment, is not a question of changing behavior, is a question of respect.

      I wont argue this at all, but this is slashdot where you are lucky people even read the article. Everybody is an asshole here and everybody cherry picks from everybody else--including myself.

      The problem then becomes, to be very blunt, if this wasn't Slashdot and everybody was respectful then nobody would have responded to you because quite honestly it was almost impossible to follow you. I honestly read your posts twice before attempting to reply--and quite frankly even that alone was more trouble than I really needed to spend. If I wasn't doing laundry right now, I wouldn't have even made it past the first sentance of your initial posts and gave up thinking "waste of time to figure out what the guy meant".

      That translates into the real world too. My inbox is full of crap and maybe only 5% is useful and actionable. Given I can't spend the day sorting it--you think I'm even going to bother wasting time parsing stuff that is hard to follow?

      How would you like if it was you?

      I'd blame it on myself and figure out what I did wrong and how I can change my behavior.

      The best advice on this topic comes from a religious text and while I dont usually quote from such things, quite frankly I've never seen this nugget better phrased:

      God grant me the serenity
      To accept the things I cannot change;
      Courage to change the things I can;
      And wisdom to know the difference.

      You can't change how people read your writing. You can get angry at them for never understanding you and consequentially never actioning on your great ideas. Instead of always being angry, you can also realize maybe the fault lies within and it would be more productive to use your energy improving your communication.

      How would you like if you were condemned to jail without an investigation?

      But you aren't. You are posting a comment on slashdot that most people aren't reading, and those that do misunderstand. ...Gotta go put more stuff in the wash.

    40. Re:Literate Programming by fabs64 · · Score: 1

      Your argument seems to be predicated on the idea that I can somehow sacrifice precision for readability and give the computer an ambiguous instruction. I can't. Computers remain deterministic no matter what my coding style.

    41. Re:Literate Programming by turing_m · · Score: 1

      My customer is the next poor slob who has to work on the source code. Software maintenance is a fact of life. Someday, somebody is going to need to read and understand what is in your code.

      And that "next poor slob" probably won't even be someone else, it will be yourself.

      --
      If I have seen further it is by stealing the Intellectual Property of giants.
    42. Re:Literate Programming by Anonymous Coward · · Score: 0

      > If we program without prioritizing the computer, we may end up writing something that may look, to us and anyone else that reads it, like what we want the computer to do, but the computer my not take it that well...

      Skynet...

    43. Re:Literate Programming by nidarus · · Score: 1

      if you say it's ironic, that means you did understand my message

      No. It's ironic "considering what you've said", not "what you've meant".

    44. Re:Literate Programming by nidarus · · Score: 1

      I didn't say people were idiots. only that they're so used to read things fast and without really paying attention.

      Even so, many people manage to get their point across on slashdot. You couldn't, and you blame everybody else.

    45. Re:Literate Programming by jeremyp · · Score: 1

      I'm sorry, but I can't help but disagree with this sentence.

      I think you miss the point. Nobody is arguing that the job of the programmer is not to tell the computer what to do. Knuth is claiming that by using the literate programming paradigm, your team (i.e. you, the other programmers and maintainers) will ultimately make a better job of telling the computer what to do.

      One must not compromise the precision of the orders it gives to the computer in order to achieve readability by something/someone else than the computer. One should, however, try to make his code as readable and elegant as he possibly can without sacrificing precision in the message to the computer.

      But we do. Simply by using a high level language, we sacrifice some of the precision of what we tell the computer. By using a high level language, you expose yourself to ambiguities in the language definition and bugs in the compiler/interpreter. You do it because the loss of precision is massively outweighed by the ease (for a human) of writing code in a high level language.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    46. Re:Literate Programming by Rene+S.+Hollan · · Score: 1

      The problem her is the background and skill set of "the next slob".

      Do I include a treatise on the merits of sliding window protocols in an implementation of a TCP stack? It makes sense if "the next slob" know nothing about networking, but is smart enough to learn. Of course, the PHB will expect us to be "interchangeable" when this is clearly not true.

      Or, do I dare presume that someone called upon to maintain network code will be happy with unsigned long wnd; /* sliding window */ in a structure as adequate documentation?

      Often one does not even know the scope of a piece of code one is given, or what presumptions were made about "the next slob" by "last slob".

      But. by far, the largest problem appears to be aggressive documentation to the level of the "lowest common denominator" expected to maintain something of the "trees" of a program, with little regard to the overall "forest" of them.

      --
      In Liberty, Rene
    47. Re:Literate Programming by blaizer · · Score: 1

      There are actually 10 kinds of people: * Those who know the binary numeral system, and * those who don't.

    48. Re:Literate Programming by turing_m · · Score: 1

      I have to hand it to you. I can virtually see your business plan.

      1. Go to slashdot, it has geeks who need to get laid.
      2. Use John C Dvorak style trolling. It's a proven concept. Couple a strawman and being purposely obtuse.
      3. The geeks most in need of getting laid will smell blood in the water.
      4. They will read your comment and start hatching their replies.
      5. They may even click on your advertisement for... wait for it... "geeks getting laid"! (I can see the VCs salivating now!)
      6. Profit!!!

      And if that doesn't work (hey, maybe those geeks may need to get laid, but they may enjoy replying to faux stupid comments even more), we'll change our destination:
      someoneiswrongontheinternet.com - a distributed computing effort to correct wrong opinion on the internet - WE NEED YOUR HELP!

      --
      If I have seen further it is by stealing the Intellectual Property of giants.
    49. Re:Literate Programming by GaryPatterson · · Score: 1

      While I can see what you're trying to say, your posts and the responses to them only underlines the difficulty of converying meaning. Code alone can't manage, and comments need to be unambiguous and clear.

      If anything, your earlier post combined with the many responses forms a good argument for more thorough commenting.

    50. Re:Literate Programming by joaommp · · Score: 1

      It's not my book and I don't earn anything with it, but hey, I'll change my signature just for you.

      Even if it's my writing that makes my comments obtuse as you put, it's not my fault that I'm not a native English speaker. So, I guess you misdirected your trolling insult. You might need to learn about the concept of a mirror.

    51. Re:Literate Programming by Anonymous Coward · · Score: 0

      Of course you have to tell the computer what to do. But the computer doesn't care about high level design, or even variable names. The point is, you can write code that will cause a computer to perform certain operations in many ways, but you should strive to write the code in the way that people after you can understand.

    52. Re:Literate Programming by Anonymous Coward · · Score: 0

      I'd suggest that you've minimal experience as a professional programmer.

      I've worked for too many years on both business applications and large-scale operating systems, and I can tell you that any moron can write bad, complex write code that more or less does what it's supposed to - that's NOT hard (although finding out why it doesn't QUITE do what it's supposed to - because it rarely does - can be fiendishly hard). Writing code that's easy to understand and change when the business or functional needs change, though - and writing it in a way that leads the next guy into a style of change that means it's STILL easy to change after it's been tweaked 6 or 7 times - now THAT's a skill worthy of its pay.

    53. Re:Literate Programming by YeeHaW_Jelte · · Score: 1

      "If we program without prioritizing the computer, we may end up writing something that may look, to us and anyone else that reads it, like what we want the computer to do, but the computer my not take it that well..."

      Computers are excellent in seperating comments from code. Pray tell me how using extensive commenting to inform other programmers of your intentions might confuse the computer ...

      --

      ---
      "The chances of a demonic possession spreading are remote -- relax."
    54. Re:Literate Programming by starfishsystems · · Score: 1

      The first thing I do when I'm getting to know an unfamiliar program is pick a couple of the methods or functions more or less at random, and read them carefully.

      After 37 years of programming, I've learned that it's critically important to understand the abilities of the person who wrote the code, in order to be able to later determine, when looking at something strange and mysterious, whether it should be treated as cleverly thought through or as just the ordinary inattentive crap that seems to be the standard for most professionals.

      Right now I'm doing a code review where All The Comments Are Capitalized And Deliver Important Information Such As We Are Now Initializing Some Variables. The program contains numerous blocks of (nearly) identical code. It contains long variable names which are clearly intended to be self-documenting: names such as iterationCounter or numberOfRowsReturned. This is code that's crying out to be cleaned up and refactored. It's funny how many chronic bugs go away when I do that.

      --
      Parity: What to do when the weekend comes.
    55. Re:Literate Programming by Anonymous Coward · · Score: 0

      High level languages are a convenience for humans, not computers. So write your code as though humans mattered.

    56. Re:Literate Programming by sartin · · Score: 1

      If Knuth had intended that one sentence to express all of the intent behind Literate Programming, he probably would not have written the whole book.

    57. Re:Literate Programming by badkarmadayaccount · · Score: 1

      What about macros?

      --
      I know tobacco is bad for you, so I smoke weed with crack.
    58. Re:Literate Programming by nidarus · · Score: 1

      What about them?

    59. Re:Literate Programming by badkarmadayaccount · · Score: 1

      When using assembly, are they part of the way you tell the machine what to do, or are they there for readability?

      --
      I know tobacco is bad for you, so I smoke weed with crack.
    60. Re:Literate Programming by nidarus · · Score: 1

      They can be used to improve readability, or as a substitute for copy-pasting code.

      If you're implying that even assembler macros are the sort of trade-off joaommp mentions, I guess I agree.

  4. "elegant code" overhead coefficient by GrimNotepad · · Score: 2, Interesting

    In my company i am the sole/lead/only developer, and as such i have my own defined best practices and i follow them adamantly, that said i have written clever couplets of code that "just work" they are commented from here to the nines yet 4-6 months and 3 projects later when it comes time to look at reviewing for a possible update in the project i can sometimes look at it and have to spend extra time to follow the elegant code around to get it "loaded" back into my head to see what i did. i think that so long as programs are written by humans who can sometimes look at it sometimes as an art form there should always be an "elegant code" overhead coefficient worked into every project update.

    1. Re:"elegant code" overhead coefficient by maxume · · Score: 1

      For the sake of discussion, could you point to some code that you think is 'elegant' rather than 'simple', 'concise' and 'clear'?

      --
      Nerd rage is the funniest rage.
    2. Re:"elegant code" overhead coefficient by Anonymous Coward · · Score: 0

      And I've wasted hours figuring out how object oriented "patterns" are supposed to work. Spent extra time to get it "loaded" into my mind. It's a huge waste of effort, institutionalized, because your typical developer can't handle straightforward abstractions like simple function definition.

      I had one peer tell me to use a factory pattern instead of using "map". Stupid. It's a functor either way, and one of them is actually readable, keeps the algorithmic code together, and separate from the data code. Even better, the functional arguments to map form a monad, so (most importantly) I can keep calling list functions on the resulting lists. Big win for readability. For exampmle:

      sort $ map {runMethod . dispatch_constructor} list_of_symbols

      The factory pattern makes some assumptions about code. The functional code codifies our assumptions. It makes them clear.

      Some OO patterns are so elegant they are just ontologically nasty. Yes, it is clever to pass around an object that represent behaviors for other classes to use. Great. Is that how you thought of objects when you first started? What kind of cognitive overhead is there for abusing the notion of an object, and coming up with a weird type system of patterns to combine?

    3. Re:"elegant code" overhead coefficient by dodobh · · Score: 1

      Using a factory when you have functional language style functions available is stupid. Take a look at Peter Norvig's presentation on design patterns in functional languages for what patterns from the GoF are redundant.

      --
      I can throw myself at the ground, and miss.
    4. Re:"elegant code" overhead coefficient by svtdragon · · Score: 1

      I don't know where things like this fit into the discussion... it's really quite a mathematical hack, and hard as hell to understand, but once you realize what it's doing, you realize it's saving a lot of time in a function that's called reasonably often.

  5. Subs and functions by A+Friendly+Troll · · Score: 2, Interesting

    A person whose code I regularly inherit seems to hate functions. He just writes subs with no parameters and uses global variables to pass information to and from them. It's awesome...

    1. Re:Subs and functions by Relic+of+the+Future · · Score: 1

      No, the person whose code *I* inherit hates functions; a single 6 to 9 thousand line behemoth strewn out to a dozen levels deep with whiles, fors, and 20-wide else-if trees is something I've seen more than once. Parameterless sub functions would be a huge improvement.

      --
      Those who fail to understand communication protocols, are doomed to repeat them over port 80.
    2. Re:Subs and functions by DarkIye · · Score: 1

      I hope you're coding a washing machine or something.

    3. Re:Subs and functions by i.r.id10t · · Score: 1

      I tend to write like that until I see a particular piece of code being used a second time, esp. from a different location. Then it is time to include it in a functions file...

      As a self taught programmer/code monkey, is there anything wrong with that?

      --
      Don't blame me, I voted for Kodos
    4. Re:Subs and functions by AB3A · · Score: 3, Insightful

      Functions have their place, Subroutines have their place. Global variables have their place. Static variables, Heap variables, and stack variables have their place. Even a Go To has it's place (in rare cases).

      The point is to use these tools in such a way that someone else can figure out what you're doing.

      On the other hand, as Albert Einstein is reputed to have said, things should be simplified as much as possible, but no farther. If the code is obtuse, sometimes it is because the programmer doesn't understand the background of what it is supposed to do. In other words, if you understand Digital Signal Processing, someone's code may look quite elegant. If you don't understand it, it looks obtuse.

      We'd all like to think that good programming is simply a matter of writing reasonably concise and well documented code. But it isn't. One needs an education on the subject being programmed. If you don't know the subject well enough, no amount of documentation is going to help you.

      --
      Nearly fifty percent of all graduates come from the bottom half of the class!
    5. Re:Subs and functions by dodobh · · Score: 1

      This depends on the language you are working with, but a general rule is to have a function do one thing, and do it well. Follow the same rules for functions as for Unix programs.

      You may find it useful to learn about Object Oriented Programming (at least about encapsulation, composition and inheritance from OO).

      Learn a functional programming language like Haskell, Scheme or LISP. Those teach you about being able to build abstractions even in your code structure and the benefits of encapsulating state.

      Learn a message passing language like Erlang (or an event driven framework).

      Being able to separate your code into small logical pieces makes it easier to understand, test and maintain.

      --
      I can throw myself at the ground, and miss.
    6. Re:Subs and functions by Graff · · Score: 1

      I tend to write like that until I see a particular piece of code being used a second time, esp. from a different location. Then it is time to include it in a functions file...

      As a self taught programmer/code monkey, is there anything wrong with that?

      Yes, there is something wrong with that.

      Technically I'm sure it all works but when you code code long stretches of code in one rambling function it becomes less focuses, difficult to read, harder to maintain, and you lose opportunities for code reuse.

      First off: readability. Write a long, technically correct paragraph with a couple of dozen sentences. Now take that same paragraph and break it up into a couple of smaller paragraphs with 3 or 4 sentences each. Which is easier to read and follow? A long stretch of code has very few natural markers that allow you to parse what the code is doing. Remember that most humans can only hold so much in their short-term memory before they need to clean house. By breaking long stretches of code into smaller functions you provide context and limit the amount of information you need to keep active to understand the code. This means that the code is easier to understand, write, and maintain.

      Another benefit is by having a couple of small functions verses one large one you make your code more modular. When your code blows up, and almost all code eventually does, it's much easier to refactor a small function than a large one. By using several small functions you limit the scope of the code you need to re-write, making the code much more easily maintained.

      A great side-effect of small functions is that you start seeing many more opportunities for code reuse. Even if you have a large function without much repetition you might still actually have some nice sections of code that COULD be reused, if they were set apart from your large function. By breaking large functions down into small parts you help yourself to recognize those clever sections of code that would do well to be encapsulated in their own function and reused.

      By encapsulating code into small, easily maintained, easily reused, functions that do a single thing well you greatly improve the quality of your code and make the job of programming much easier. Sure, what you are doing works for you and changing it might cramp your style for a bit but if you do make the change and stick with it you will become an even better programmer - especially when you work with others.

    7. Re:Subs and functions by Logic+and+Reason · · Score: 1
      Functions allow you to give a piece of code a name; good names make code far easier to read. They also let you read algorithms at a higher level, ignoring implementation details until you need them. Which is easier to grasp quickly: several hundred lines of code in multiple blocks, or something like the following?

      updatePaymentInfo();
      processSubscriptions();
      sendNotifications();

      Readability is important even if you don't expect anyone else to ever have to maintain your code. It helps you spot bugs more easily, and makes it much easier to jump back in after not having touched the code for a year or so.

    8. Re:Subs and functions by Anonymous Coward · · Score: 0

      Oh My Gosh, Yes. In general, you're going to want to think about the task a bit before you start (don't overdo it), and break it down into component pieces. That is to say, decompose the task into smaller tasks (Reusability is not the only concern here) - and then write out a program flow using only those "mega tasks". Then do the same thing for each of the mega tasks, creating smaller tasks, and so on. Try to keep function size between 3-5 lines and the size of your head (physically, line it up next to the monitor).

      Let's take the good old "Make a peanut butter and jelly sandwich". It has several parts:
      - Get out the stuff to make it
      --- Peanut Butter
      --- Jelly
      --- Bread
      --- Butter Knife
      - Apply stuff to the bread
      --- Peanut Butter(slice1)
      --- Jelly(slice2)
      - Squish the slices together(slice1, slice2)
      - Enjoy (return sandwich)

      So your main func would look like:

      int main(int argc, char ** argv)
      { ...declarations...
              get_items_for_making_pbj_sandwich(...args...);
              apply_stuff_to_pbj_sandwich(...args...);

              pbj_sandwich sandwich = squish_bread_together(slice1, slice2);
              enjoy_pbj_sandwich(sandwich);

              return 0;
      }

    9. Re:Subs and functions by Anonymous Coward · · Score: 0

      > if you understand Digital Signal Processing, someone's code may look quite elegant. If you don't understand it, it looks obtuse.

      Fair enough, but if you don't understand the problem domain, you probably shouldn't be monkeying with the code anyway!

    10. Re:Subs and functions by A+Friendly+Troll · · Score: 1

      Functions have their place, Subroutines have their place. Global variables have their place. Static variables, Heap variables, and stack variables have their place. Even a Go To has it's place (in rare cases).

      The point is to use these tools in such a way that someone else can figure out what you're doing.

      Yes, that is true.

      But in my case, for example, a variable named "i" (obviously for "integer") is used in a million places. The only way to figure out how something works is to run everything through a debugger, step through, and use pencil and paper to map the flow of the variables from one sub to another. Sometimes one sub will "accept" "i" and "return" "i", sometimes it will place the result in "ii". Sometimes the code will throw you a red herring because it will "return" the result but it won't be used anywhere else in the process; well, of course, the tenth sub in the chain might overwrite it so that the eleventh may use it, and god help you if you've missed the tenth sub and thought "why the fuck is the eleventh sub doing this when 'i' was 5 just a moment ago?!".

      The code is usually beyond fixing. It takes more time to figure it out and refactor than to properly rewrite everything from scratch after asking the end user what a certain part of the application should be doing.

      Coding practices are nice and all, but they can't get around idiots. To put it differently, a lack of unified and useful coding practices is merely a minor inconvenience, whereas a programming moron is a clusterfuck.

    11. Re:Subs and functions by i.r.id10t · · Score: 1

      So the idea piece of code would just be a collection of function definitions, and then a series of calls to those functions. Even if none of the functions were called more than once?

      Wow.

      (And yeah, I've played with C++ and Java in school but our instructors weren't qualified to teach finding your butt with both hands)

      --
      Don't blame me, I voted for Kodos
    12. Re:Subs and functions by Steeltoe · · Score: 1

      Of course this is what you get for using global variables in local loops.
      You should teach the user about the use of local variables over global scope, and how he can even use a bit more creativity and use names like account_counter or row_index, or something other than "i". "i" is over-used when clearly a more descriptive name can even save you some comments, by conveying enough information just by its own name and general use..

      E.g. This is a BAD comment: /* loop from 0 to 100 */
      for (i=0; i=100; i++)

      This doesn't need much comment other than maybe a higher-level one:
      for account_index=0; account_index = 100; account_index++)

    13. Re:Subs and functions by Logic+and+Reason · · Score: 1

      So the idea piece of code would just be a collection of function definitions, and then a series of calls to those functions.

      Perhaps. I tend to do that only at the highest level of an algorithm, because below a certain point it gets annoying to jump around from function to function so much. It's also usually not just a simple set of sequential, no-argument function calls like in my example; I was just trying to give some examples of the kinds of one-use functions I would write.

    14. Re:Subs and functions by Anonymous Coward · · Score: 0

      That may reflect his history. Code for a few years on one main language then switch to another, and I can guarantee that a decade later you'll still have distinctive habits from the first language. (I started writing mostly in PL/I; I now write mainly in COBOL. It took me a gob-smacking number of years to stop faking up bit flags and start using level 88 conditional variables instead.)

    15. Re:Subs and functions by Anonymous Coward · · Score: 0

      A person whose code I regularly inherit seems to hate functions. He just writes subs with no parameters and uses global variables to pass information to and from them. It's awesome...

      It's called "RPG".

    16. Re:Subs and functions by rwiggers · · Score: 1

      That's some assembly programmer writing something in another language. I see it all day long...
      Usually that's an EE who never had a lesson on programming and learned it on the field 40 years ago.

    17. Re:Subs and functions by CrazedSanity · · Score: 1

      When I first started coding, I did everything inline: no functions, classes, or anything. Then I saw code that was mostly functional, and noticed how much easier it was to use a function to avoid duplicating code all over the place. The object orientation came later, and was a very welcome addition, as it helped to split things into specific (or generic) containers for storing and manipulating data.

      That said, I feel that moving things into functions is very important, even if that function is only called once. Putting things into functions forces you to define exactly what is happening in a way that allows it to be reused. This also helps with introducting unit-testing or other types of testing to ensure your code is running properly.

      --
      Sanity is like a condom: rather have it and not need it, than need it and not have it.
    18. Re:Subs and functions by CrazedSanity · · Score: 1

      Being able to separate your code into small logical pieces makes it easier to understand, test and maintain.

      Well said! Bravo!

      Breaking code into smaller logical pieces is paramount to making it maintainable. When you or someone else goes to maintain it in the future and finds there is a problem with a specific portion, such as with writing data to the database, they should be able to find the database portion and trace back from there.

      A good example of this principle of logic separation is with code that interacts with a database. I've worked with some custom PHP code that had a lot of interaction with a database, but all the connections were done directly when needed instead of using a class (or even just a function). The effects of this decision had a ripple effect:

        * parameters to the connections had to be given inline
        * connection strings had to be globally accessible, though were regularly hard-coded
        * SQL had to be written & executed inline
        * checking for rows returned/rows affected/errors had to be done for each call manually
        * code was regularly created via copy/paste
        * variable re-use often caused errors (previous call was successful, last call wasn't, but variable continued to have a successful appearance)

      The first thing I would have done, had I been allotted the time, was to integrate an abstraction layer for the database. Separating this logic would have allowed for the ability to write-out SQL statements to a text file for analysis--which is very helpful for determining where a database can be optimized (i.e. better indexes, etc).

      This specific level of separation would also allow for moving to a different database with a smaller impact on the code: modify a smaller set of code to connect to a new DBMS, then use it to track any issues resulting from the new database. Not only does it help save time, but it avoids rewriting a ton of code!

      --
      Sanity is like a condom: rather have it and not need it, than need it and not have it.
  6. Best practices only go so far... by djpretzel · · Score: 3, Informative

    "Quality" can be both objective and subjective, and it seems this post is leaning towards the latter in terms of what it's getting at... while I believe in having formalized guidelines of some kind, I've found the best way to seek out and improve the elements that can't be easily quantified is through (drum roll) code reviews/walkthroughs. It seems like these are rare, at least where I'm at, and it's hard to get buy-in when you're talking about contractors charging by the hour, but in my opinion a single quality code review can save TONS of time down the road and is necessary for projects over a certain size. Also, read "The Pragmatic Programmer" and "Code Complete" for some of the best guidance on this topic.

    1. Re:Best practices only go so far... by nietsch · · Score: 1

      So true. Because contractors are expensive, money people think that less is better. To get something done on time, little or no time will be spent on testing/review. Ugly hacks will always continue to 'work' which is what the client pays for.

      --
      This space is intentionally staring blankly at you
  7. What's worse that no documentation? by johnlcallaway · · Score: 4, Insightful

    Incorrect documentation.

    And the only correct documentation is the code itself. Anything else is a opinion and should be viewed accordingly.

    In other words, when it comes to reading documentation ... trust .. but verify!

    I don't know how many times over my 30 year career that I've read documentation and started work only to find out later that it hadn't been updated. The first standard in your documentation rules should be that all relevant documentation is created and updated before code goes into production. No excuses.

    If it doesn't have that .. then the documentation is unreliable at best, and dangerous at worst.

    --
    I rarely read replies, it's my opinion and if you thought about your opinion a little more, I'm OK with that.
    1. Re:What's worse that no documentation? by GrimNotepad · · Score: 1

      best comment i have ever seen in the code i inherited is //insert comment here

    2. Re:What's worse that no documentation? by PolygamousRanchKid+ · · Score: 1

      My favorite was in tcp_input.c in BSD code:

      "This is ugly, but . . . "

      --
      Schroedinger's Brexit: The UK is both in and out of the EU at the same time!
    3. Re:What's worse that no documentation? by mclearn · · Score: 1

      I've always wondered if there was any (automated) way to at least give developers a fighting chance when dealing with out-of-date documentation.

      My only experience using a source code manager is CVS -- sorry. But I'm sure SVN and Git are similar. CVS understands the sections of code that have changed. There are also numerous ways to parse languages. Can we not combine the two to determine if there is a so-called "significant" change (where this is a highly questionable quantifiable value) and, if so, reject the check-in unless the comment directly above it, beside it, (or whatever) has changed as well? Perhaps there are already tools that do this? I am not aware of them and I would be most interested if anyone has anecdotal stories about things they use at their workplace to try to automate this.

      Of course, nothing will stop a motivated developer from eventually getting around such a stop-gap system, but this would be designed to HELP, not PREVENT.

    4. Re:What's worse that no documentation? by Lord+Pillage · · Score: 1
      I came across a macro-laden hell one time when I was going through some C code with a comment:

      This is right, but I hope the compiler can sort it out

      This was followed by something like A(B((C(D))D(C))A2(C))....

      --
      try { Signature mysig = new CleverAttempt(); } catch(NonCleverSignatureException e) { postanyway(); }
    5. Re:What's worse that no documentation? by gbjbaanb · · Score: 1

      my favourite is: // TODO: quick hack to make it compile. Needs fixing before checkin

    6. Re:What's worse that no documentation? by Coryoth · · Score: 1

      And the only correct documentation is the code itself. Anything else is a opinion and should be viewed accordingly.

      Of course the code itself only tells you what the code does, not what the code is supposed to do, nor why it is doing it. Note that the difference can be rather crucial in maintenance and bug fixing.

      I don't know how many times over my 30 year career that I've read documentation and started work only to find out later that it hadn't been updated. The first standard in your documentation rules should be that all relevant documentation is created and updated before code goes into production. No excuses.

      Which is why it's always nice to have documentation that can be tested against the code. Now the "why" part of documentation is rather hard to verufy against code, but the "what it is supposed to do" should be able to be automatically verified if it is sensibly written: for instance in Eiffel requires and ensures clauses, or in JML, or splint, or SPARK; which allow for varying levels of static checking, runtime assertions, and automatic unit test generation (depending on what you are using) to ensure that if code and documentation falls out of sync an error should be immediately flagged.

    7. Re:What's worse that no documentation? by dkf · · Score: 1

      the only correct documentation is the code itself

      Sounds like you've not done very much maintenance programming. The problem is that the code is often wrong too. So now you've got to figure out what it was supposed to do originally (good luck, the developer's left the company under a cloud and didn't leave a forwarding address) and also what all the clients of the code are expecting it to do (typically at variance with what the code does and what it is supposed to do). At that point, reading the code doesn't help very much. Yes, you know that it is setting certain flags in an indirectly-accessed context by performing a calculation and then XORing the result, but do you know if they are the right flags? Were they ever correct? Did the meaning change from then and the calculation not get updated? Who knows?

      External documentation should cover the high-level design of the system; the principles upon which it is all founded. That doesn't change very fast (total replacement of the basic data structure of a program is hard, and rarely done). Comments on the code (plus sensible naming of functions, arguments and variables) should cover how the big picture fits to the local view of what is going on. It's rare indeed that you need blow-by-blow comments on each line of the function; that's when reading the damn code itself ought to suffice. (The code itself only ever says "how"; it never says "why", and only says "who" and "when" in the most cryptic fashion. For maintenance, "why" is the key question.) An objective spec (which can be external, but which most certainly isn't the code) makes it easier to say whether the code is right or wrong, and if wrong, how it can be fixed or improved without causing difficulties. A spec does not need to be long either; lots of functions are characterized by just a line. Refusing to comment at all is just ridiculous and malicious.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    8. Re:What's worse that no documentation? by martin-boundary · · Score: 1
      You know, your comment is both interesting and sad. I've heard and accepted this point myself (about comments being out of sync with code) for many years, and it's still a problem. But why? This is a classic problem that a code editor should be able to solve. Yet I've never seen an Emacs mode or a vi mode that fixes it. Maybe it's like colour highlighting: obvious in hindsight, but it still took decades for people to think of it?

      Here's what a code editor *should* be doing: if you edit a piece of code (function or block etc), then if there are any comments near that code, it should mark the comment as possibly obsolete. This could be as simple as wrapping a string "POSSIBLY OBSOLETE" around the comment, or changing the colour of the comment etc. The details are unimportant, what matters is that the code editor can automatically (and non-destructively) make explicit that said comment is no longer to be relied upon by the next programmer, whenever that occurs. Of course, the current programmer might also rewrite the comment or just "touch" it, ie explicitly guarantee that the comment is still relevant with the new code.

      This won't solve every problem with comments, but it's something useful that a code editor can do automatically.

    9. Re:What's worse that no documentation? by johnlcallaway · · Score: 1

      While I agree the 'why' is important, coders don't always know 'why', they code to something because somebody told them to. For instance, I work for a company that does financial analysis for portfolio managers. I don't have the slightest idea why specific algorithms are used, guys with PhDs have done their own analysis to determine the algorithms. They suck at coding like I suck at financial analysis, so they give them to me to implement into production. (Any monkey can write code that works at their desktop, it's my job to make it work every day within performance parameters and with appropriate error checking and restart capabilities). While I know what 12 month rolling averages, closing price, stock volumes, and standard deviations are, I don't know why they are being used they way they are.

      Any company of a decent size should be hiring less programmers and replacing them with technical writers if they haven't done so. Having coders writing documentation doesn't work, they won't be able to do it well and it only annoys them. Coders can document inline where necessary and leave the real documentation to people that actually have an aptitude and desire to write. Then the the coders can review their work for accuracy since they love to find mistakes in other people's work. The technical writers should be able to pull all the necessary information together so the 'why' and 'how' questions are all answered in a manner that is useful.

      This has the added advantage of not pulling a programmer off of documentation work that he will never get back to for an important project.

      --
      I rarely read replies, it's my opinion and if you thought about your opinion a little more, I'm OK with that.
    10. Re:What's worse that no documentation? by johnlcallaway · · Score: 1

      Dude .. that is ALL that I do and have done for most of my 30 year career. I now specialize in coming in after some new-degree guy who wants to write in some 'cool' tech the he also has no experience in, then proceeds to write it so poorly that no one else wants to touch it. All I often have is the original spec to depend on, and sometimes I find that isn't right either, the developer made changes BECAUSE it wasn't right.

      Code is never 'wrong', it always does what it is programmed to do. My point is that one CANNOT depend on the spec or the documentation to tell them what a program does. Read the spec and documentation to understand what it is supposed to do, then read the code to make sure it does it. And if someone can't figure the code out, then they aren't as good as they think they are at maintenance programming.

      If the code, documentation, and specs disagree, all you know for certain is that for the last 10 years, the code has been running in production this way because that was the last time it was compiled. That doesn't make it right, but you had better find someone to explain it.

      Ok .. to be fair, sometimes I don't even know if I have the right source code either. Sometimes you just have to start over....

      --
      I rarely read replies, it's my opinion and if you thought about your opinion a little more, I'm OK with that.
    11. Re:What's worse that no documentation? by xiong.chiamiov · · Score: 1

      And that's why we don't accept changesets that don't include documentation updates.

    12. Re:What's worse that no documentation? by dcam · · Score: 1

      Code never lies. It may mislead but it never outright lies.

      --
      meh
    13. Re:What's worse that no documentation? by dkf · · Score: 1

      If the code, documentation, and specs disagree, all you know for certain is that for the last 10 years, the code has been running in production this way because that was the last time it was compiled. That doesn't make it right, but you had better find someone to explain it.

      If code, docs and specs all disagree then you've got problems. Doubly so if the code doesn't appear to correlate at all with the behavior of the deployed program. I've seen that (someone had patched the binary for unknown reasons...)

      When you're working with componentized software, it's more important to be spec driven. This is because the consumers of the code usually work according to the spec (most programmers aren't too keen on having to read someone else's source just to find out how to use it). In those cases, it's also easy to have a feature that is only rarely used and which doesn't work (e.g., by crashing, a clearly undesirable situation). If that happens, you're stuck with working out whether this was a problem of the spec or the implementation or the documentation (i.e., if the component was just called wrong). Sometimes life's like that.

      Of course, even better than the spec is having the design theory of the code. That's because it allows you to know how the original author was envisaging evolving things, and it lets you know which parts are just code that was put in to make it work and so can be improved/fixed without trouble. With the design theory, you can even re-derive the spec from first principles. But yes, it's often (even usually) missing, as most junior programmers just don't grasp why it is important and so never write it down.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
  8. Review the Code by RAMMS+EIN · · Score: 4, Insightful

    Review the code that gets checked in (you are using version control, are you?). If it doesn't obviously do what it is supposed to do (including the case where it is not obvious what it is supposed to do), something is wrong.

    You can spend any amount of time writing best practices, but that doesn't ensure they are good, workable, and actually applied. In the end, what matters is if other people can understand the code. And you can measure that by just having them do that. As an added bonus, you get more people familiar with the code.

    --
    Please correct me if I got my facts wrong.
    1. Re:Review the Code by dkleinsc · · Score: 1

      One of the really good practices out there is reviewing code in a group. You pull in 3-4 developers (besides the one who wrote the code). The one who wrote the code explains what it was intended to do. Another developer goes through line-by-line and describes what it actually does. Lots of nits are picked, but in the end what you usually get is useful critiques for the developer who wrote the code, and some good ideas from that same developer that other developers use.

      If mis-applied, this sort of thing would be annoying bureaucracy, but when done properly the result is that all developers are learning what works and what doesn't from each other, and the code that gets put into the code base gets better.

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
  9. who said that? by turbidostato · · Score: 1

    90% of code is rubish. Which should come to no surprise since 90% of everything is rubish.

    The point here is that there're not so much qualitatively different high-level solutions to "the art of programming". The fact that after 30/40 years of repeating basically the same (obvious) things most of us can't cope with its basics shows the obvious: 90% of coders are rubish. The fact that 90% of coders think about themselves to be in the other 10% doesn't help, either.

    1. Re:who said that? by Anonymous Coward · · Score: 0

      90% of code is rubish.

      This is an important insight, that the vast majority of code is, in fact, written by rubes.

    2. Re:who said that? by Anonymous Coward · · Score: 0

      Gee, you must be a blast at parties!

  10. Stop reading the code, stupid! by Anonymous Coward · · Score: 1, Funny

    Works for congress.

    1. Re:Stop reading the code, stupid! by TimSSG · · Score: 1

      We really need an option "+1 frighting".

      Tim S.

  11. Not Here! by Anonymous Coward · · Score: 1, Insightful

    I wouldn't ask here. Some of the worst code advice I've ever seen comes from Slashdot, especially from the idiots who think all programming is like their PC or Linux box. The worst are those that think Java is suitable for everything, or that what's good for the web is good for every situation.

    1. Re:Not Here! by nietsch · · Score: 1

      Quality of advice is not measured by the worst piece, but but the quality of the advice you take to heart. So who cares that someone recommended java for kernel programming? If only the best is good enough, you get nowhere fast. accepting different opinions and using your own head gives you better ideas, because you can discard the bad ones. The OP came here for good ideas...

      --
      This space is intentionally staring blankly at you
  12. Comments and standard libraries are useful by TheLink · · Score: 1

    Even if they themselves aren't useful, they might give you an idea of how crap or "clever" the code is at some point ;).

    Anyway, to me one very important good coding practice is using standard or defacto standard libraries where possible instead of rolling your own (unless it means using those libraries in "rube goldberg" ways, in which case roll your own).

    Because it means less to document, maintain and also it makes for easier debugging - because when you see "standard library method/function" you know what it does, you don't have to look it up and check it.

    Whereas if the program is filled with custom library methods (even when standard ones that do the same thing exist) you will have a lot more work to figure out why and whether they do what you think they do and what they are supposed to do.

    And that's why in the real world, writing in certain languages is better than in others, if it means you end up writing less code of your own. It doesn't matter if the language is so cool and powerful that you can write code that does zillions of stuff, but if it means you have to rewrite lots of stuff that would be standard in other languages, it's not as maintainable.

    Yes in some scenarios you want a powerful language that helps you in the code that you write. But in most scenarios, you'd want a language that helps you in the code that you don't have to write ;).

    --
  13. Train your programmers by Alain+Williams · · Score: 1
    He gives a few things that he calls CRAP and then goes on to extol the GNU programming style. I do agree that documentation is key, the problem is that many people say that they will ''add the comments after the code is debugged'' - this is what is wrong, you write the comments when you write the code, if you change the code 6 times you change the comments 6 times.

    I fear that he is really trying to bring everyone down to the level of the novice programmer rather than raising the standard. I have met managers like that, they say things like ''we won't do that here'' (meaning: ''I have not seen that construct before and am afraid of something new''); ''goto is forbidden'' (meaning: ''someone important said goto is harmful'' - not having understood that Dijkstra was talking about code where 25% of statements were goto - in the days fore things like while loops).

    We need to educate programmers, make them better - not dumb down programming.

    1. Re:Train your programmers by Blakey+Rat · · Score: 1

      We need to educate programmers, make them better - not dumb down programming.

      One of these things is possible, the other is not.

      Making programming simpler isn't "dumbing it down" it's making the power of computers accessible to more people. I frankly can't imagine why anybody would object to that.

    2. Re:Train your programmers by Anonymous Coward · · Score: 0

      if you change the code 6 times you change the comments 6 times.

      This seems to directly contradict the well-known and oft-quoted ethos - "Comments aren't how, they're why". If your code rewrite involves lots of small changes to the "how" of the code, but the "why" is still fundamentally the same, why should you change your comments?

  14. What is clear to one ... by WoodstockJeff · · Score: 3, Insightful

    I work in an environment where there are 4 programmers, of varying skill. What is "clear" to one is not necessarily clear to another, even if it is straight-forward coding. For example, I might program a loop to iterate through an array of data, extracting the important information, while another might explicitly write out each iteration, because he is less familiar with arrays. His code is quite clear - but inflexible, and subject to errors if he makes a required change to 19 of 20 copies of the calculations. Mine is quite clear, but subject to some obscuration if there's something special that has to be done in 3 of the 20 iterations.

    In the case of TFA, if the author were this other programmer, he might consider my code to be "too clever".

    Much was made of the use of "obscure" variables. Yes, that's one I dislike a lot, too... but I haven't made too much progress on that score in 25 years, with regard to others. When you're working on code that requires a lot of manipulation of a variable, typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

    1. Re:What is clear to one ... by Relic+of+the+Future · · Score: 2, Insightful

      typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

      Learn to use autocomplete.

      --
      Those who fail to understand communication protocols, are doomed to repeat them over port 80.
    2. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      Exactly - verbosity (I mean not in variable names, which should be descriptive, but in how the code is written) makes things easier for novice programmers, but has a serious maintainability cost. I've worked on highly complex pieces of software, and constantly struggle with this: when a change in behaviour is needed, I can accomplish it with a few lines changed in 5 minutes, but several others spend a week re-writing large amounts of their code because the required thing is not well encapsulated.

      There's an inverse relationship between the level of abstraction and expressive power. I believe in high levels of abstraction coupled with well commented code and long-ish descriptive names. Others favour high levels of abstraction with terse names, which is very hard for anyone else to make sense of. Yet others favour low levels of abstraction because they do not understand the higher level ones. The problem with that approach is that there can be many orders of magnitude difference in what such "low abstraction" programmers can accomplish. I'll take a shop of 5 programmers highly proficient in powerful techniques, over one of 75 "low abstraction level" programmers.

      Excessive code verbosity also has an obscurity all its own. When I see 60 lines of code doing what could be done in 1 or 2 lines, it's very hard for me to read such code, because not very much functionality fits on my screen at once. I can't see the high level picture because the low level details are taking up so much space.

    3. Re:What is clear to one ... by tepples · · Score: 1

      Learn to use autocomplete.

      Then how do I teach an editor to allow autocomplete for a given language?

    4. Re:What is clear to one ... by Jeremi · · Score: 1

      When you're working on code that requires a lot of manipulation of a variable, typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

      Only in a language that doesn't require you to explicitly declare variables. In a reasonable language, any typos in your long variable name will result in compile-time errors and will therefore be caught and fixed the next time you compile the program.

      In fact, the only time when a typo in a variable name should compile is if there is another variable declared with the typo name. The chances of that happening are much smaller when you're using long variable names than short ones.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    5. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      meta-x given-language-mode

      as the gods of Emacs intended. or, if you are a god of Emacs, start writing the elisp module.

    6. Re:What is clear to one ... by corbettw · · Score: 1

      Use a modern editor that can store the strings of all previously used variables and allow for autocompletion when you start typing them. Emacs does this, vim does this, countless IDEs do this. Take your pick.

      --
      God invented whiskey so the Irish would not rule the world.
    7. Re:What is clear to one ... by ysth · · Score: 1

      That's exactly the source of bugs. Typing out by hand a long descriptive name will either be correct or (in a decent language) a compile error. Using autocomplete allows you to get the wrong variable without noticing, and doesn't always get a compile error.

      (Nevertheless, descriptive variable names are well worth it.)

    8. Re:What is clear to one ... by James+Youngman · · Score: 3, Insightful

      Goodness, how did that person get hired as a programmer if they weren't already fully familiar with arrays? I wouldn't hire anybody as a programmer unless they were able to select an appropriate data structure for a problem, and explain why they selected that particular one. (Well, at my current employer, the bar is much higher than that, but I'm speaking in general).

    9. Re:What is clear to one ... by coryking · · Score: 1

      Using autocomplete allows you to get the wrong variable without noticing, and doesn't always get a compile error.

      Assuming you are using a strongly typed language (C#, Java, etc) this is not a big deal. Namely because the odds of getting the wrong variable *and* the same type are pretty low.

      For example you've got a string "HappyString" and a int, "HappyInt". If you wanted HappyString.Replace("hello", "world"), if it somehow thought you meant "HappyInt.Replace()", the compiler would blow up because int's dont have Replace().

      Course, I can't really think of a time my IDE gave me the wrong variable (unless we are talking about case issues--HappyString vs happyString). I'd think if your IDE is always auto-completing with the wrong variable, your IDE probably really sucks and you should find a new one.

      If we are talking languages like Perl, PHP, Javascript and whatnot, things are different--obviously.

    10. Re:What is clear to one ... by ysth · · Score: 1

      Don't include Perl in that list, unless you mean non-strict script-kiddie Perl.

    11. Re:What is clear to one ... by coryking · · Score: 1

      As a Perl nerd myself, I'll include Perl too... I'm not talking about variable declaration, I'm talking about the fact that nothing is strongly typed.

      It is an inate part of the language that makes it challenging to create intelligent IDE's that know the following snippet doesn't really make much sense:


      my $HappyString = "Hi"

      Fun($HappyString);

      sub Fun {
          my $hashRefHere = shift;

          printf $$hashRefHere{'key'};

      }

      Yeah that will compile, but it is really a bug in your code (you passed basically a string to something that wants a hashref). Your IDE will never in a million years be smart enough to figure out that Fun($happyString) is a bug.

      Nothing wrong with it, but it is just the nature of the language. Perl (and PHP, javascript, Python, Ruby, etc) dont do that kind of thing. The compiler and the IDE both need to know that the function Fun() wants only a hashref:


      my [string] $HappyString = "Happy";

      # ERROR: Cannot pass [string] into Fun(), expected [hashref]
      Fun($HappyString);

      sub Fun {
          my [hashref] $myHashRef = shift;
      }

    12. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      You can resolve this pretty easily with a code cross reference.

    13. Re:What is clear to one ... by WoodstockJeff · · Score: 1

      Well, let's see... when it's the person who hired you that isn't "fully familiar with arrays", because he's the one that started the company, maybe you can "do the math".... ;)

    14. Re:What is clear to one ... by js_sebastian · · Score: 3, Insightful

      typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

      Learn to use autocomplete.

      If you have autocomplete then you can probably also hover your mouse over the variable to get a little window with the documentation for it... So use that, STFU, and let me use variable names I can type reliably and possibly even pronounce.

    15. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      Emacs, duh. There are plenty of free frameworks that allow you to define your own completion mechanisms, but I bet one exists for your language of choice already.

    16. Re:What is clear to one ... by maxume · · Score: 1

      Most of the languages you are talking about are strongly typed (in that objects have a type and usually a new object needs to be constructed to get similar information as a different type), but also dynamically typed (meaning that variables are not restricted to a single type).

      They support different levels of ugly when it comes to automatic type coercion, of the ones I am at least passingly familiar, php is the worst, javascript is in the middle and python does okay (php and javascript will both coerce something like '1' to a number, python will not).

      Also, you are vastly underestimating the state of the art in type inference; I don't really know much about it, but Haskell does a lot of it, and there are compilers for subsets of python (Shedskin is one of them) that do lots of the type inference that you are implying is impossible.

      --
      Nerd rage is the funniest rage.
    17. Re:What is clear to one ... by dkf · · Score: 1

      Well, let's see... when it's the person who hired you that isn't "fully familiar with arrays", because he's the one that started the company, maybe you can "do the math".... ;)

      In that case "the math" says to me that it is time to look for another job where the owner won't be sabotaging you with abject stupidity. Just sayin'.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    18. Re:What is clear to one ... by mikael · · Score: 1

      These days, there seem to be so many different ways of processing array data now, many of which seem to be mutually exclusive, multi-threaded code /OpenMP/MPI/TBB vs. STL / templates, that manually assigning/incrementing/testing an array index/loop pointer is a bad way of doing things.

      Under STL, you just have an iterator that goes through the data structure, with just an initialize, increment and test functions. With some of the parallel processing macros, you just have a forall(array) above a pair of parenthesis with the individual tasks.

      At all the companies I interviewed for, they would have a series of test questions at a particular level - either how to manually manage linked lists (embedded device drivers), how to implement data structures using STL (R&D) or how to implement multi-threading (parallel processing applications).

      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    19. Re:What is clear to one ... by Blakey+Rat · · Score: 1

      When you're working on code that requires a lot of manipulation of a variable, typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

      Maybe you should upgrade to an IDE built sometime in this century.

    20. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      Dam programers and all his clever languages I cannot understand! "i++"?! WTF...
      "Increment(i);", is much better, but wait! what about "increment i;"? Or better yet: "Increment the variable named i", but it may be best: "increment the number stored in memory under the name i", or "remember that number I just gave to you? yes, that one that was like 3 or so. That's it. Now, can you please make it 4?, thanks."
      Much better, isn't it?

    21. Re:What is clear to one ... by WoodstockJeff · · Score: 1

      The IDE I use is current and actively developed, updated just two weeks ago, thank you very much. It has syntactically-aware auto-completion, and lots of other features of "modern" IDEs. It even supports copy/paste! ;)

      Except it isn't emacs, or written in Java, so I guess that disqualifies it as being "modern".

      If this weren't /., I'd suggest knowing what you're typing about before doing so.

    22. Re:What is clear to one ... by Blakey+Rat · · Score: 1

      What are you talking about? Emacs is an abomination. Eclipse is ok, but Java is a deal-breaker for me. I was referring to just any IDE with variable name auto-complete.

      How are you using an IDE that's syntactally aware but doesn't have auto-complete? WTF.

    23. Re:What is clear to one ... by Blakey+Rat · · Score: 1

      Wait, I misread. It has auto-completion-- then why would you complain about variable naming?

      A lot of complaints in this thread can be resolved by just using the features of your IDE.

    24. Re:What is clear to one ... by Anonymous Coward · · Score: 0

      For me its not even a matter of the time to type the variable. For me, it's easier for me to grok the full meaning and function of a (errr) function, the less characters there are on the screen cluttering up my view. Functions which run longer than a full screen size at the minimum possible font size really should be split up some into smaller functions.

      But even for functions which aren't horribly long, shorter names end up being quicker and easier for me to visually parse than long complex names.

      Trying not to confuse two variables named superReallyLongNamedVariableWithTonsaWords from reallyLongNamedSuperVariableWithJustAsManyWords slows me down as a reader compared to inVar and varTemp. The later ones may not describe the variable quite as fully, but for ease of reading, once I figure out what they stand for, I prefer the shorthand versions. And if your variable naming strategy has resulted in a variable name which is wider than one screenful of text, you should have your programming license revoked.

  15. Literate Programming by Anonymous Coward · · Score: 1, Informative

    Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

    The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style.

    The language which provides the capability to achieve all these goals is called COBOL. Ever heard of it?

  16. Baffled, what ancient age are you from? by mauddib~ · · Score: 1

    I'm baffled. Here we use extensive extra documentation, mostly outside of the code. Programming changes are related to changes in design documents and deployment documents. Also most of the design follows UML diagrams which are thoroughly kept together with all programming code. As far as we use programming code, every change is reviewed by another developer. Without these, we would quickly lose our minds, heads and bodies to the massive complexity.

    I always thought NASA was one of the top quality software engineers, but apparently not in every department.

    --
    This is a replacement signature.
  17. Keep it simple by yog · · Score: 5, Insightful

    the op has it mostly right. There's little value in fancy show-off code that may earn a programmer some machismo points from like-minded colleagues but results in maintenance headaches down the line.

    Elegance is often misused to mean terse, clever code, but that is really far from what elegance ought to mean.

    I define good, elegant code to be code that is clear, well commented, self-explanatory, and easy to modify.

    I'm dealing right now with some "object-oriented" Perl programs that are nearly comment-free. Sure, eventually it'll start to look familiar and I'll know where to go to fix stuff, but it pisses me off at the programmer.

    I don't want people cursing and mocking my name after I've left a position, so I always strive to make my code as obvious as possible, at the cost of some high falutin' fanciness that just bogs people down and keeps a company from getting its business done efficiently.

    To me, the highest compliment is when a newbie says "I just read your {Java|Perl|C++|SQL} program and I was surprised at how easy it was to understand. I just wanted to thank you for that."

    --
    it's = "it is"; its = possessive. E.g., it's flapping its wings.
    1. Re:Keep it simple by UnknownSoldier · · Score: 5, Insightful

      > well commented,

      Many programmers don't understand that concept:

      * Code tells you 'how'
      * Comments tell you 'why'

      I have found this to be _especially_ important for bug-fixes. Very important to document why things were done a certain way to minimize implicit side effects.

    2. Re:Keep it simple by Twinbee · · Score: 1

      I suppose the clearest code of all would often have exponential run times, zero optimization, extremely inefficient disk access routines, and of course, very short code.

      I would die for that day.

      --
      Why OpalCalc is the best Windows calc
    3. Re:Keep it simple by Simon80 · · Score: 2, Interesting

      Mod parent up! I think that comments should tell you 'what', as well as 'why', in cases where 'what' isn't synonymous with 'how'. When changing existing code, I like to know what the original author's intent was, so I can tell if certain aspects of the existing behaviour are coincidental side effects of how the code was written, or deliberate choices by the author.

    4. Re:Keep it simple by w3woody · · Score: 2, Insightful

      Absolutely spot-on. I would say, however, there is one exception: if you have code that is implementing a complicated algorithm, such as implementing insert or delete from a B-Tree using an algorithm pulled from a book like Knuth, or performing an algorithm found on Wikipedia, I'd document the original source of the algorithm. Thus while the code tells you "how", the comment tells you where you can find out more about "how".

    5. Re:Keep it simple by pjt33 · · Score: 1

      And both you and GPP hint at comments also telling you "what not and why not".

    6. Re:Keep it simple by lwsimon · · Score: 1

      I seem to swap between comment styles on th fly -- if I'm writing a simple wrapper function, I see no need to comment every two or three lines. If I'm writing a complex view for a webapp with imbedded business logic, i'm going to want to make sure that the individual rules are well commented.

      --
      Learn about Photography Basics.
    7. Re:Keep it simple by Migala77 · · Score: 1

      Many programmers don't understand that concept:

      * Code tells you 'how'
      * Comments tell you 'why'

      I have found this to be _especially_ important for bug-fixes. Very important to document why things were done a certain way to minimize implicit side effects.

      Yes.
      These can be comments in code, but SVN (or any SCM) commit comments are also extremely useful for this.

    8. Re:Keep it simple by dkf · · Score: 1

      These can be comments in code, but SVN (or any SCM) commit comments are also extremely useful for this.

      Those tell you who, which is useful for getting back at them when you find that something "clever" was deposited in code you maintain. I know of devs who always commit with a message "fix the bug". Thankfully, they use genuinely good commenting practices or I'd be forced to hunt them down and put them out of my misery.

      The advantage of comments is that they're right there in the code when you're looking at it. Commit log messages typically need an extra step to retrieve (especially when you've got a complex and old file, when identifying who committed the core of the code you're looking at, and not just the last change to it).

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    9. Re:Keep it simple by arjan_t · · Score: 1

      These can be comments in code, but SVN (or any SCM) commit comments are also extremely useful for this.

      I fully agree with that. That's why I usually go out of my way to persuade the developers in my team to write good commit comments. Of course, source code typically can't be attached to an SCM forever, but in most production environments it typically is (or well, should be...).

      Next to commit comments, don't forget a link to an issue, ticket or bug (e.g. Jira, Trac, Bugzilla) that was the reason for the code to be written or modified. I see well written tickets and commit comments as an integral part of the code's documentation. Now some people only see a ticket as an order to do some work and thereafter discard the ticket. With such a view, you don't write your tickets in such a way that you still understand a year later what the issue was. E.g. tickets like: "Fix the prod. problem that bothered bob this afternoon". For me such tickets are worthless.

    10. Re:Keep it simple by Anonymous Coward · · Score: 0
      Never any mod points when you need them (Days like these are when I wish I hadn't changed ids)

      I can almost always figure out what the code is doing but I don't know why it is doing it. What were they thinking when they put this strange special condition in there? Oh yeah the comment says "Jira/BugTracker/Error XXXX Special business rule ..." Put the dang business rule or ticket number near the funky code!

      We require bug / change request numbers for all commits but that doesn't always tell you which part of that ticket the change is for.

    11. Re:Keep it simple by LordArgon · · Score: 1

      Checkin comments should tell you more than just "who". Otherwise you wouldn't need the comments (just a checkin log). They're for giving context on the entire change set and they should always be provided. You can't write a code comment on a file you just deleted - you just deleted it. And you don't want to include references to obsolete structs / classes in your comments - then you're confusing your code comments with your version tracking.

      Checkin comments like "fix the bug" are downright lazy and should always be hunted down. :)

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

      Thanks! That seriously needs to be in more basic programming textbooks. I've never had a good guideline for how to use comments beyond "don't write too much nor too little" Knowing the goal of comments is much more useful.

    13. Re:Keep it simple by turbidostato · · Score: 1

      "That's why I usually go out of my way to persuade the developers in my team to write good commit comments."

      In my experience you must teach them how to do proper commits first!

      For too many "new generation" developers, commits are too much alike "Ctrl-S" so first you need to explain them "commit" is not shortcut for "save" and that while a commit is not needed to include a whole functional change (it depends on local practices, though) it should add a significant meaningful change. Only *then* they'll be able to add a meaningful commit message (like "bug#1234: the employee list now returns proper values for subcontrated people as per spec#101". It can be much better than this, but this is the bare minimum).

    14. Re:Keep it simple by MadKeithV · · Score: 1

      * Comments tell you 'why'

      Usually in the form of "Bug number 1234567: I don't know why this fix works, but it does. Don't touch it!".

    15. Re:Keep it simple by kbielefe · · Score: 1

      I agree on your definition of elegance. "One-liner" and "elegant" rarely belong in the same sentence, in my experience. Elegant code generally is shorter than the most obvious solution, but for me to call it elegant, it must also be immediately understandable by even relative novices. Elegant code is best recognized when you maintain it. If you think a change will take hours until you look at the code and can do it in a few minutes, you're looking at elegant code. There is a feeling of "of course that's the best way to do it" that is obvious even to novices in hindsight, but would likely only occur to an expert in foresight. If only an expert can understand it, it's not elegant code, at least in my book.

      --
      This space intentionally left blank.
    16. Re:Keep it simple by badkarmadayaccount · · Score: 1

      I wonder if a compiler can treat imperative statements as declarations, and add in some simple AI to do high-level peep-hole optimization (on the algorithm level).

      --
      I know tobacco is bad for you, so I smoke weed with crack.
    17. Re:Keep it simple by Twinbee · · Score: 1

      Part of me doubts that if it can't even be shown whether arbitrary code will complete or not (Halting Theorem).

      Still, yes, that would be awesome.

      --
      Why OpalCalc is the best Windows calc
    18. Re:Keep it simple by Anonymous Coward · · Score: 0

      Gotta disagree with the "Comments tell you 'why'". Sure, if you're doing something fancy, out of the ordinary, or difficult to understand, write a comment telling me whythe code is written that way. However, the comments I find the most useful in others' code are the ones that give me a BRIEF description of what a block of code is intended to accomplish.

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

      > the comments I find the most useful in others' code are the ones that give me a BRIEF description of what a block of code is intended to accomplish.

      Well, duh. "what a block of code is intended to accomplish" = "purpose" = "why"

    20. Re:Keep it simple by Simon80 · · Score: 1

      It's probably better to separate as much of the implementation as possible from the business logic, e.g. by factoring out the view logic. You don't want to over-engineer anything, but at the same time, if you know certain code is likely to change, you want to factor out the parts of it that aren't likely to change as frequently. Comments are probably still useful, but they aren't a replacement for abstraction, where it's warranted.

    21. Re:Keep it simple by meowhous · · Score: 0

      Comments lie; only code tells the truth.

      You can be badly mislead by believing what the comments say the code is doing. An ancient programming text from the 70s had the advice that when reading code, you should cover up the right hand side of the page (this was back in the FORTRAN days, so only some of us will remember that columns 72-80 weren't code).

      I've worked places with execrable coding practices in regards to coding, e.g., that all comments must be passed through a spell-checker and grammar-checker before checking in the code. (Right.) Luckily, I didn't have the appropriate security clearance to read the Coding Standards document, so I happily just wrote good code. (Until I got caught at it.)

      That rant over, I do like the occasional comment as sort of a guidepost as to what previous developers might have intended the code to do. But I never trust it.

  18. Lowest Common Denominator by Anonymous Coward · · Score: 0, Insightful

    Why should I write my code so that the lowest-common-denominator dull thud who took CSci just for the money can come along five years later and maintain it? I agree that good coding practices produce readable code. But too often this whole topic leads into the idea that all code should be McCode, meaning blah standards-conforming blocks, often not even approaching the best possible solution to a problem.

    Sorry. Not a priority. And no, I don't care that you won't hire me. You want an assembly line slinger. And will pay accordingly.

    1. Re:Lowest Common Denominator by tepples · · Score: 3, Insightful

      Why should I write my code so that the lowest-common-denominator dull thud who took CSci just for the money can come along five years later and maintain it?

      No, so that you can come along five years later and maintain it.

    2. Re:Lowest Common Denominator by corbettw · · Score: 1

      Don't worry, CmdrTaco. I may not hire you, but I'll keep visiting your site.

      --
      God invented whiskey so the Irish would not rule the world.
    3. Re:Lowest Common Denominator by middlemen · · Score: 2, Insightful

      Why should I write my code so that the lowest-common-denominator dull thud who took CSci just for the money can come along five years later and maintain it?

      No, so that you can come along five years later and maintain it.

      Or your future boss can outsource it to some peanut-salaried person in Eastern Europe or Asia or Latin America or Nigeria.

    4. Re:Lowest Common Denominator by Anonymous Coward · · Score: 2, Interesting

      Who stays at the same coding job for 5 years? If you're actually good at your work, you will be getting offers from other companies that include large raises long before then.

      Um, maybe someone who actually cares about doing quality work and improving the business? When I look at a resume with a bunch of 2 year stints at various companies, I will immediately think, "Great, here's a jackass code-jockey who will wander in, piss all over my group's code, and then leave as soon as someone else offers him an extra $1.50/hour. Pass."

      That said, I also believe in rewarding quality work, so if you're doing well for me, you'll get those raises without needing to jump ship. But perhaps I'm a rarity in business these days...

    5. Re:Lowest Common Denominator by dcam · · Score: 3, Funny

      Five years, feh. I can't barely recognise the code I wrote 3 months ago.

      I regularly look at some code and say, "who wrote this crap?". After checking the history I find it was me.

      --
      meh
  19. Code Reviews (Gerrit) by jtolds · · Score: 2, Informative

    Traditional everyone set aside time and review checked in code is hard to do, difficult, and time consuming.

    On the other hand, automated code review tools are life changing. There's a bunch of tools out there, but the one I think is far and away the best is Google's Gerrit tool (http://code.google.com/p/gerrit/), which is what Google uses publicly for Android.

    I cannot understate how helpful Gerrit has been in this regard. So many things that are trouble down the road are easily caught by even just one other pair of eyes. Everyone who has used Gerrit at my compnay has fallen in love with automated code reviews. It's refreshing, leads to better code, etc. I seriously could gush about Gerrit for pages.

    1. Re:Code Reviews (Gerrit) by gbjbaanb · · Score: 2, Informative

      It seems that's for git only, if you want a similar code review product (that's web based) you could look to VMWare's OSS ReviewBoard which is more source-control tool neutral (requires python) and can be automated according to your SCM tool.

  20. The same logic isn't common in everyone by techhead79 · · Score: 1

    As we all know just about every coder has their own way of doing things. Each person has found the solution to common programming steps differently. This flow of logic is carried over to larger programs and new logic that must be considered to answer more complex coding problems. There is no one way to write a program and this means there are a thousand different ways each person could come up with the logic paths to answer the question. Clever cures boredom and does what every programmer should be doing...making their program more efficient....

    What makes sense to one person is a combination of how they answered similar problems and other coder's answer to similar problems. There are many hacks in the industry that cause a lot of problems for code readability. They are not clever, they are the other extreme where they barely understand what is even going on. Any real coder though can see the difference between being clever and being a hack, it usually involves comments carried over from what program they gutted to get their's to work. I think it's important to separate those two types of problems.

    Once you take out the hacks you should be able to see how any coder reached the logic they did. Rewrites because of logic doesn't just stand at the one coder required to maintain class xyz. Shit falls down hill. If the overall design is flawed, if the requirements are not clearly outlined, if someone high up keeps changing their mind..then the coder at the bottom of the hill doesn't stand a chance at writing long term good code. Anyone that's worked in a project knows there is this odd relationship that forms. You have the heavy coders, you have the logic gurus looking at the bigger picture and delegating, you have the do what you cans that are left the scraps after the heavy coders get their work, you have the project leaders which hopefully will be writing code too, you have the project owners that write no code, you have the upper management barking orders. There isn't just 1 person responsible for good code even if there is just 1 person writing it.

  21. communication is key, not just documentation by Kartoffel · · Score: 2, Insightful

    One person's clever, obscure trick is another person's common practice.

    Communicate with the other coders in your project. Write decent comments. TALK to the other coders. Cooperate and share ideas.

    1. Re:communication is key, not just documentation by lytles · · Score: 1

      One person's clever, obscure trick is another person's common practice.

      i guess i'm the evil programmer type - i read the article for the sake of seeing some clever tricks. i stopped reading after his first example ... not clever at all, not obscure at all, no need to comment, no need for fancy variable names, no nothing ... and i don't think i've coded in c in 5 years

      for(ss = s->ss; ss; ss = ss->ss);

      if there's any ambiguity about what that line is doing, you're not qualified to be commenting on anyone else's code

    2. Re:communication is key, not just documentation by Anonymous Coward · · Score: 0

      My thoughts exactly. This snippet is plain as the sun for any C coder.

    3. Re:communication is key, not just documentation by surmak · · Score: 1

      I also fail to see what the issue the author has with the code he quoted:

      for(ss = s->ss; ss; ss = ss->ss);

      All that this does is set the variable ss to NULL, if s is a well-formed linked list with the ss field serving as the pointer to the next node. If the list is circular, you have an endless loop.

      I'm assuming that the original did not have the semicolon at the end and was actually doing some processing in the body of the loop.

      In any case, the only issue I see with this code is overloading ss as both a field in the linked list, and as a local variable.

    4. Re:communication is key, not just documentation by XSpud · · Score: 1

      It's not ambiguous but it's a lot easier for a human to parse something like the following:

      for (node = list->ss; node; node=node->ss);

      Another advantage of the latter is that if that section of code is buggy it's clear what the author intended whereas for the original anyone debugging the code will need to consider whether there's a simple 1 character typo e.g.

      for (ss=ss->ss; ss; ss=ss->ss); could also make sense depending on context.

      Why make it more difficult than it needs to be?

    5. Re:communication is key, not just documentation by rwiggers · · Score: 1

      How would you talk with the coder when you're being hired for his position?
      that's just one case of many when talking isn't possible. Documentation should be written, and well written.

  22. Optimize all the time... for clarity by noidentity · · Score: 2, Insightful

    Optimization is fine, as long as you're "optimizing" the code to be more clear. This is a good way to redirect the energy that programmers often put into pointless performance optimization. Most understand that optimizing for one thing often de-optimizes somthing else, so they understand that you can't optimize for speed and clarity in many cases. Always looking for ways to make code clearer can become an enjoyable habit, as optimizing for speed is for many. Then you spend your idle moments eliminating many lines of code that you realize are unnecessary, bringing the code closer to its essence. My experience anyway.

  23. I've ignored this non-problem for years by OrangeTide · · Score: 1

    At the last few places I've worked we found that just ignoring this problem long enough lets it just go away. People who have style and coding practices that are bad, end up changing them eventually or leaving. And people with good practices tend to have success with their software, even if the styles end up being different from one another.

    If you can't wait for the problem to sort itself out, then try hiring a bunch of good people that have worked together before.

    --
    “Common sense is not so common.” — Voltaire
  24. Practices.. by JoeZilla · · Score: 1

    When will people finally realize that defining and documenting practices alone doesn't make good code? You need good programmers that care and that monitor each others and (more junior) programmers' code quality. Encourage feedback between the programmers, etc.

  25. The only thing which counts for businesses by kipsate · · Score: 1

    is releasing new functionality as quickly as possible. Timelines counts, not code quality.

    One of the classic arguments between manager and coder is about how much time should be invested in cleaner code, since, as most coders would argue, such investment earns itself back because new features can be implemented faster when having a nice and tidy code base.

    Managers of course often get their ways and coders reluctantly give in, mumbling about code becoming unmaintainable.

    Investing in code quality is indeed risky:

    - Even despite poor code quality, the coders know their stuff and implement new functionality without any problems;
    - After investing in code cleanups it may soon turn out that this particular functionality is no longer required and all this nice and tidy code has been developed for nothing;
    - "Cleanups" may end up in overly complicated code which turns out to be even more difficult to maintain than the original code base.

    --
    My karma ran over your dogma
    1. Re:The only thing which counts for businesses by presidenteloco · · Score: 1

      Yes, but messy code is guaranteed to become unmaintainable within 2 years or so.

      What happens is, a manager cracks the whip on programmers, gets the credit for
      getting the "messy" program done on schedule and budget, gets promoted to other
      responsibilities, and is at a safe distance when the bomb goes off.

      This issue seems structural in software development within business, but I wonder if
      it is avoidable in a more casual schedule open-source project.

      I also got a comment from a Google exec one time that "they don't really have schedules"
      for software developments. They wait til they're ready.

      You can say that's because they're rolling in dough, but you've got to wonder how did they
      get to that position? Maybe enlightened management from early on played a big role.

      --

      Where are we going and why are we in a handbasket?
  26. Rule of thumb by xororand · · Score: 4, Insightful

    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

    1. Re:Rule of thumb by Anonymous Coward · · Score: 0

      "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

      Okay, that's cute, but I'd rather the mod point attribution be "Funny" rather than "Insightful."

      If you write the code as cleverly as possible, you are, by definition, writing the code as cleverly as that code can be written. You're not necessarily writing it at your maximum capacity to think, reason, or write code in general.

  27. The solution to bad comments is good comments by Anonymous Coward · · Score: 0

    There is no such thing as self-documenting code. A block of code without comments, no matter how well-written, is an order of magnitude slower to work with than code with just a couple of sentences at the top explaining what is going on and why. I find this "comments are always out-of-date anyway" argument baffling. If that's the problem, then the solution is to make keeping comments up-to-date a key part of the requirements, not to omit them entirely.

    If someone lacks the discipline or intelligence to update a simple sentence after making a change, then their 'self-documenting code' is not something I ever want to see.

  28. All code is obscure to the incompetent. by Anonymous Coward · · Score: 0, Insightful

    for(ss = s->ss; ss; ss = ss->ss);

    Pretty standard way to traverse a linked list.

    1. Re:All code is obscure to the incompetent. by jlowery · · Score: 1

      To get to the first 0 pointer in the list? Perhaps, but what if the list is very large? Wouldn't a wrapping class that maintains the list's last node work faster?

      What do 's' and 'ss' stand for?

      --
      If you post it, they will read.
  29. Sane source control is critical by Antique+Geekmeister · · Score: 1

    Using good source control helps, a lot. I've gotten very fond of git and its ancestror for style though not code, BitKeeper, because they let you do work locally and submit it centrally when you're ready.

    Also, if your "coding standard" isn't built into your editors and common tools, you're doing something wrong. For example, if your C++ standard is not consistent with 'indent', you're doing something wrong.

    1. Re:Sane source control is critical by mindstrm · · Score: 1

      I like git to - but in the end, it's just easy branching and merging. The same development methodology can (and should) be used in many situations with those. With git, it just comes naturally.

      (each developers work is on a branch, and merged back into the appropriate target branch when they deem it ready by the appropriate manager.

  30. Soem of the complaints aren't valid by tomhudson · · Score: 3, Insightful

    If you have a variable that is a rating of employees at an organization, organizationEmployeeRating is not a ridiculous name, while erating is.

    If you have a method that calculates the risk of an investment, name it calculateRiskInvestment(), not risk().

    erating is fine, especially if it's in a struct, to give you the context, or when it's first declared: int erating // employee rating

    risk() is also better. Since the author says its a method, it's in a class. Investment.risk() is a hell of a lot better than Investment.calculateRiskInvestment().

    The author is complaining because the code is all in c. Awww - c has different style conventions. Don't try to make it look like java.

    1. Re:Soem of the complaints aren't valid by AmberBlackCat · · Score: 3, Insightful

      "erating // employee rating" requires you to look in the comments of the declaration section in order to figure out what the variable does, whereas "organizationEmployeeRating" tells you what it is no matter where you see it in the code...

    2. Re:Soem of the complaints aren't valid by tomhudson · · Score: 2, Interesting

      If you're going to be maintaining it, you'd better damn well look over more than just the immediate code. Look at the declaration, instead of assuming what it is. There are too many pieces of code where people asume the type of a variable, "fix" the code, and make things worse.

      3 most important rules

      1. ALWAYS look at the variable declaration.
      2. ALWAYS look at the variable declaration.
      3. ALWAYS look at the variable declaration.

      ctags is your friend. Even the laziest f*** can learn how to use it in a minute or two.

      If you can't use ctags and/or fgrep effectively, you shouldn't be touching c code. You're simply not qualified.

    3. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 1, Insightful

      Exactly. Use ambiguous terms like erating if you want to ensure that other people are going to have to do global searches on erating in order to figure out what it means.

      One of the most insidious ways of introducing bugs is by loosely defining the exact the purpose and value range of a variable, and one of the first steps to reduce that problem is by using an unambiguous name. (That said, I wouldn't embed a variable's acceptable value range into its name -- that should be taken care of with unit tests and assertions, and noted in comments or docs.)

    4. Re:Soem of the complaints aren't valid by tomhudson · · Score: 1, Troll

      Exactly. Use ambiguous terms like erating if you want to ensure that other people are going to have to do global searches on erating in order to figure out what it means.

      I would want anyone maintaining the code to look at the declaration to make sure they know what type it is, then look at any initialization code, before monkeying around with it.

      That's what ctags is for.

      It even supports php, javascript, perl, make and shell scripts - it's not just for c any more.

    5. Re:Soem of the complaints aren't valid by Graff · · Score: 3, Insightful

      risk() is also better. Since the author says its a method, it's in a class. Investment.risk() is a hell of a lot better than Investment.calculateRiskInvestment()

      At a glance, does Investment.risk():
      - return anything
      - change the state
      - perform validation

      Yes, Investment.calculateRiskInvestment() is overkill and redundant but Investment.risk() is not clear enough. A good compromise is Investment.calculateRisk() or Investment.getRisk(). You know what action it is taking and what it is acting upon.

      There is overkill in both directions, variables and method names that are too verbose and ones that say too little. The trick is finding a nice balance and, most importantly, having a very predictable and consistent naming convention.

    6. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      What the fuck C compiler are you using? C isn't as strict as a language like Haskell, but with even a shitty compiler at least you'll usually get some sort of a compiler warning, if not an outright error, if you try to do something epically stupid using a variable of the wrong type.

      The only places I've seen type errors like that happen is when you're using a language like Ruby, Python, Perl, Tcl or PHP. Some of them don't even bother to try warning you of your mistake, they just make blatantly stupid conversions (like from a floating-point number into a string) automatically. Those conversions WILL fuck you and your code over, repeatedly and repeatedly.

    7. Re:Soem of the complaints aren't valid by Krahar · · Score: 1

      Exactly. Use ambiguous terms like erating if you want to ensure that other people are going to have to do global searches on erating in order to figure out what it means.

      I would want anyone maintaining the code to look at the declaration to make sure they know what type it is, then look at any initialization code, before monkeying around with it.

      I would want anyone writing code to look it over closely to ensure that no simple bugs have crept in. Unfortunately, we know that this is impossible to do - programmers write simple bugs, even the ones with 40 years of experience and an IQ of 200. That is why you should do everything you reasonably can to make bugs apparent, and choosing meaningful variable names is one of those things. Saying that people should read X or Y at some other place in the code may be a good idea, but it ignores that simple mistakes happen however much you try for them not to.

    8. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      Of course everyone should read the declaration and initialization before reading it, however by using a vague or incomprehensible token for the variable requires them also to memorize all such token strings in the code for the lifetime of the dealings with their code. This is because erating has no logical connotations to anyone but the person who wrote it (who may well also forget what it means later), whereas organizationEmployeeRating has an obvious meaning to it and will trigger associated memories for that concept.

      If it's okay to have a very vague, ambiguous variable name then why would it not be okay to have an extremely vague variable name? Why not simply call it r? If you're worried about name collision or being able to search for it, then simply pad the name and call it something like r________. Have a program full of R_____s and t#######s and z_______s. Try to seriously imagine what that'd be like, because that is how other people feel when they look at your code full of eratings.

    9. Re:Soem of the complaints aren't valid by tomhudson · · Score: 1, Insightful

      Riiiight ... you've never seen anyone compare a signed integer to an unsigned integer or vice versa ...

      ALWAYS look at the variable declaration and the initialization code.

    10. Re:Soem of the complaints aren't valid by tomhudson · · Score: 0, Troll

      whereas organizationEmployeeRating has an obvious meaning to it and will trigger associated memories for that concept.

      ... and it's SO obvious that when someone DOES change it, nobody else is even going to bother to check, because it's "obvious" what it means. Something can be both obvious and wrong, and the use of java-style retarded naming conventions in c code is a source of both consternation and bugs. c is not java. If you're not comfortable with c, go back to interpreted languages like java and perl. (yes, java is interpreted at runtime - get over it already).

    11. Re:Soem of the complaints aren't valid by Zero__Kelvin · · Score: 1

      The statements you have "quoted" appear nowhere in the parent, or even in this particular subthread. Congratualtions on showing how people who think erating is a fine variable name tend to introduce unreadability wherever they tread ;-)

      --
      Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    12. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 1, Informative

      I've done that myself. Any decent C compiler should issue at least a warning.

      Take GCC, for instance:

      $ cat > warning.c
      int main(int argc, char *argv[])
      {
          unsigned int i = 5;
          return argc == i;
      }
      $ gcc -W warning.c
      warning.c: In function 'main':
      warning.c:4: warning: comparison between signed and unsigned
      $

      If you're not requesting warnings from your compiler, then you're a fucking moron. It doesn't matter which compiler you're using.

      Tom Hudson, if you're truly getting caught by that sort of a problem, then you clearly have no idea what you're doing, and I sure hope that you don't pass yourself off as a programmer of any type.

    13. Re:Soem of the complaints aren't valid by Toonol · · Score: 1

      If you're not comfortable with c, go back to interpreted languages like java and perl. (yes, java is interpreted at runtime - get over it already).

      Hmm... you seem to have gone from discussing to ranting. I HATE Java, and cringe when I have to run a Java program... but even I know that Java is sometimes interpreted, sometimes compiled. And even if it was always interpreted, it's juvenile to get mad and start trying to insult people over it. Nothing wrong with interpreted languages in the first place, and they aren't innately less sophisticated or complex.

    14. Re:Soem of the complaints aren't valid by Chees0rz · · Score: 2, Insightful

      This whole thread has a bunch of snotty nosed C programmers using the annoying, pretentious, absolute statement:

      "If you do/don't do X or Y, you shouldn't be touching code / aren't a programmer / should quit now / suck at life."

      Get a life. There are better ways to give advice than insulting the person while you do it.

    15. Re:Soem of the complaints aren't valid by Chees0rz · · Score: 3, Funny

      (That said, I wouldn't embed a variable's acceptable value range into its name -- that should be taken care of with unit tests and assertions, and noted in comments or docs.)

      You know somebody didn't make it this far in your comment and there is now a variable out there somewhere named averageClassGradeOfStudentsInMrsTwomblysClassIn PortlandHighSchoolZeroToOneHundredMaybeOne HundredAndTenIfTheyGotBonusPoints

      (I had to add a space... /. got mad at my long string...)

    16. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      Indeed. My policy on production code is always "no warnings with -Wall in release config". If it's a debug config, I might allow a one or two warnings of the "variable set but never used" type, provided I know exactly why they occur. Even that is a luxury I would not give myself had I thought anyone else would touch the code any time soon.

    17. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      If you're going to be a crotchety old ranter, could you please do it at the beginning of a discussion so other people know enough not to waste their time trying to have a reasonable exchange of ideas with you?

      At least now I finally know it's not worth it to point out that you ignored my main points, or that your most recent point -- which makes erroneous assumptions in both cause and blame -- even if true would argue against the use of vague pseudo-english, like you suggest, and towards the use of completely vague gibberish-type variable names that would *insist* on the user looking up the variable's definition, and hopefully not be memorable in the context of other variable names.

      Anyway, enjoy your crotchety old manness. Don't worry, I'll keep off your lawn.

    18. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      Or you could just use a language that requires you to define _everything_ like Ada, instead of arguing about method names all day on slashdot.

    19. Re:Soem of the complaints aren't valid by lukas84 · · Score: 5, Funny

      There are better ways to give advice than insulting the person while you do it.

      But giving advice without insults is called consulting and costs money.

    20. Re:Soem of the complaints aren't valid by Korin43 · · Score: 1

      organizationEmployeeRating is annoying to type though. How I usually get around this is by using non-descriptive variables as I write (I'd probably just use "rating"), and then use Netbeans to rename the variable organizationEmployeeRating when I'm done (for other people's benefit).

    21. Re:Soem of the complaints aren't valid by BlitzTech · · Score: 1

      My kingdom for some mod points... :D

    22. Re:Soem of the complaints aren't valid by owlstead · · Score: 1

      Investment.getRisk() looks too much like a getter method to me, so it might confuse others as well. I hate it when "getters" actually do meaningful calculation (outside just relaying state of the object) or worse, change state. I saw a method called getData() that actually performed an HTTP request at my company. That object now has "deprecated" written all over it.

    23. Re:Soem of the complaints aren't valid by Magtheridon · · Score: 1

      Most of these complains are entirely valid.

      C has a different style convention because it comes from a time when program performance was the key issue, hardware costs were high and programmer costs were low.

      Java-like conventions are around because hardware costs are low and programmers are what costs more. It is more efficient to have a programmer spend less time working on a project then have everything small and tidy.

      On this note, however, method/variable names are treated the same by the compiler no matter their length, so having long names that describe an issue well come at no hit to efficiency.

      One of the most important things for code understandability is modularity, breaking code into well defined sections that make it clear what each part of the program is doing- and is responsible for.

      One-liners should be reserved for command-line run once scenarios.

    24. Re:Soem of the complaints aren't valid by jeremyp · · Score: 1

      I disagree. erating might be OK if it's in a struct of type Employee, but then why do you need the e? In other contexts "employeeRating" is better because it means the maintainer doesn't have to go back to the definition to find out what it is.

      risk() is also better. Since the author says its a method, it's in a class. Investment.risk() is a hell of a lot better than Investment.calculateRiskInvestment()

      I would say that depends. If it's an accessor for a property, I think "risk()" is better. However, if it's the implementation of a method to calculate risk, "calculateRisk()" is better.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    25. Re:Soem of the complaints aren't valid by DudeTheMath · · Score: 1

      LOL. Wish I had mod points.

      Back to TFA, though, I consider "for (ss = s->ss; ss; ss = s->ss)" canonical C (although, yes, I would *probably* have used slightly more descriptive variable names and field names).

      --
      You save only 59 seconds over 8 miles by going 75 instead of 65. Do you really have to pass that guy? Do the Math!
    26. Re:Soem of the complaints aren't valid by SETIGuy · · Score: 1

      Yes, Investment.calculateRiskInvestment() is overkill and redundant but Investment.risk() is not clear enough. A good compromise is Investment.calculateRisk() or Investment.getRisk(). You know what action it is taking and what it is acting upon.

      Dividing up the calculation of the investment risk and returning the investment risk to a caller is poor design of the Investment class to begin with. You are requiring any program using the class to know whether calculateRisk() has been called since this instance or anything that it depends upon was last modified.

      The proper design would have a unified method to calculate and return the risk. That method would check whether the Investment instance or anything else that affected the risk calculation had changed since the risk was last calculated. If so it would recalculate the risk, if not it should return the risk value that was previously calculated.

      This could involve a private methods called calculateRisk(), a private const method called getRisk(), and a (possibly public) method called hasBeenModified(), but anyone using this class should be calling the public Risk() method using the documented interface. It will be obvious from the code that Risk returns a value.

      risk=investment->Risk();

      Someone who looks at that code and wonders what Risk() does and whether it modifies an Investment instance or any static variables should be looking at the class documentation and/or the appropriate header file rather than guessing based upon what the calling code does. But a proper class design shouldn't allow someone to obtain the risk value before it's calculated, nor should it allow a caller to calculate the value if they aren't going to use it. Both of those fit into the "bad idea" category.

      Some is going to possibility that Risk() has desirable or undesirable side effects. Well, it shouldn't have any that can be detected by a caller using documented interfaces. If it does, then it shouldn't be called Risk(), it should be called ReturnRiskAfterSortingInvestmentsByCEOsMothersMaidenName().

    27. Re:Soem of the complaints aren't valid by Skal+Tura · · Score: 1

      And you should keep a consistent naming scheme, along with consistent typecasing....

      investment.calculateRiskInvestment() // investment.calculateRisk()

      and int employeeRating

    28. Re:Soem of the complaints aren't valid by tomhudson · · Score: 1

      There are some things that are just so common and obvius that "proper typecasing" is a waste of time. For example, cdate, mdate, adate (creation, modification, and access dates), uid, gid (user ID, group ID), umask, ibuff, obuff (input and output buffers), tz, recno, rval. cDate, mDate, aDate, uId/uID, gId/ gID, uMask, iBuff, oBuff, tZ, recNo and rVal are just visual pollution.

    29. Re:Soem of the complaints aren't valid by Krahar · · Score: 1

      A getter IS just a method that does not change any state. The whole point of encapsulation is that you as a client of an object should have no clue what the data representation inside the object is. If there was such a rule that a method starting with "get" could only return a member variable, then you might as well expose the variable itself in the first place, since you've just removed the whole point of having any method starting with "get" - the point being that it aids encapsulation since you DON'T know that it is in fact just returning a member variable. You might have some expectation that a method starting with "get" does not spend too long in computing its result, but that's it and it isn't something you can really rely on. Now a getXYZ method that does change the state of the object, that's just evil.

    30. Re:Soem of the complaints aren't valid by Krahar · · Score: 1

      getRisk is still so much better than Risk.

    31. Re:Soem of the complaints aren't valid by Tablizer · · Score: 1

      I've had long and heated debates about abbreviations in variable names. A compromise for the above would be EmpRating or OrgEmpRating along with the comment. That'd be my preference. Too long and they make code harder to read. However, I've come to realize that it's a subjective personal preference and different people will want it different. I know what my eyes and brains like and you know what your eyes and brains like, and we are all different.

      Another suggestion is to look at frequency of use. The more often a variable is used, the more shorter/abbreviated it's name should be. If something is used often, then you're gonna know what it's for anyhow. No use hogging screen space for it.
         

    32. Re:Soem of the complaints aren't valid by physicsnick · · Score: 1

      Unless you're coding in Java, I definitely don't agree with the Java-style getRisk(), because the 'get' is redundant. Accessor methods usually take no arguments and return a value, so the fact that they 'get' something is obvious. Google's C++ style advocates risk(), as does Apple with Objective-C (the default accessors for properties even work this way).

      I would call it calcRisk() if it is not const, i.e. it modifies the Investment object somehow (and calc is common short form for calculate). If however it's a const method that just returns the risk, then putting calculate in front is unnecessary. In fact I'd argue that advertising the fact that it is calculated on the fly is a violation of encapsulation. What if you find out that calculating the risk is slow, so you'd like to pre-calculate it, and just return the stored value? calculateRisk() is now mis-named (and you get your grubby hands all over everyone's code and logs if you rename it.)

    33. Re:Soem of the complaints aren't valid by Graff · · Score: 1

      Investment.getRisk() looks too much like a getter method to me, so it might confuse others as well. I hate it when "getters" actually do meaningful calculation (outside just relaying state of the object) or worse, change state.

      It is a getter. The thing is getters aren't just for simply echoing variables, they are also used to format encapsulated data from inside an object to hand off to the calling code. In this case the risk level is being gotten from the Investment object. It's a perfect use of a getter, even if the getter is doing the calculation on the fly. Risk might not be a stored value in the object but it is still an attribute of an Investment.

      As for getters changing state, they shouldn't affect the object in such a way that is immediately obvious to an outside observer. However, they can do stuff like keep a running count of accesses, cache the results of calculations, and so on. Performing a HTTP request is definitely stretching it, I could see the argument for doing that but it'd be a tough sell.

    34. Re:Soem of the complaints aren't valid by Graff · · Score: 1

      The proper design would have a unified method to calculate and return the risk. That method would check whether the Investment instance or anything else that affected the risk calculation had changed since the risk was last calculated. If so it would recalculate the risk, if not it should return the risk value that was previously calculated.

      Well, of course!

      Someone who looks at that code and wonders what Risk() does and whether it modifies an Investment instance or any static variables should be looking at the class documentation and/or the appropriate header file rather than guessing based upon what the calling code does.

      I agree with this too. All I'm saying is that your code is so much more readable if you have a bit more than just risk(). It's certainly not a substitute for reading documentation and understanding the code, but a bit more verbose and carefully-chosen method name will jog your memory more easily and it stands out better than a terse method name. I'm not saying that calculateRisk() is the best name but it's a lot better than just risk(). I personally feel that getRisk() is even better and that's closer to what I'd use.

    35. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      Investment.risk()

      Somehow I got the feeling from the article that the author wasn't talking about object-oriented code when ranting about risk(). In OO, function names needn't be so verbose because object names gives implicit information to the function. On the other hand in C, functions aren't implicitly tied to anything. Therefore you need to explicitly express the same information.

    36. Re:Soem of the complaints aren't valid by owlstead · · Score: 1

      OK, OK, but you'll agree with me that calculateRisk() would be a much better name for the method. What if the calculation takes lots of time? A getRisk() would not convey that possible meaning to me. It would easily be skipped when looking through the code for easy optimizations (and e.g. other persons could call a getter twice instead of saving the result in a local variable, for instance). So why not use calculateRisk() instead of getRisk()? Better safe than sorry.

      As for the state, I think we are in full agreement here.

    37. Re:Soem of the complaints aren't valid by owlstead · · Score: 1

      Hmm, I don't count cached results or a running count of accesses as state of an object.

      The first one is just an optimization that does not tell anything of the actual state of the object - clear the cache and the state is the same.

      The second one is a clear cut case of meta-state. The state of the use of the object, not of the object itself.

      And yes, of course you may use a getter to do calculations to reveal the state of an object. If the getter however starts to perform a calculation that could take a lot of time, or if the calculation is not directly related to the state of the object, you'd be better off using calculateRisk() than getRisk()...

    38. Re:Soem of the complaints aren't valid by Graff · · Score: 1

      Unless you're coding in Java, I definitely don't agree with the Java-style getRisk(), because the 'get' is redundant. Accessor methods usually take no arguments and return a value, so the fact that they 'get' something is obvious. Google's C++ style advocates risk(), as does Apple with Objective-C (the default accessors for properties even work this way).

      I do a lot of programming in Objective-C and honestly I don't agree with Apple on this one. (Not that they need MY approval!)

      Yes, the words "get" and "set" are a bit redundant but they are only 3 extra characters and they make scanning through code much easier. When you are reading code it is often helpful to easily see if a method is returning a value. I'd even argue that "set" is much less important than "get" because you can easily see that method takes an argument and is a setter, in fact most IDE autocomplete features fill the argument in for you. It's a lot harder to determine, just by glancing, if a method returns a value or performs an action so the prefix "get" provides valuable information.

      setter:
              investment.setRisk(number); // obvious, passes in number to risk
              investment.risk(number); // still pretty obvious, passes in number to risk

      getter:
              something = investment.getRisk(); // obvious, returns a value for risk
              something = investment.risk(); // not obvious - does this return a value or does it perform an action on the object and then return the object?

      It's pretty bad in Objective-C too:
              something = [investment getRisk]; // the message "getRisk" is a getter and returns the value for that property
              something = [investment risk]; // is the message "risk" a getter or does it do some action and then return the receiver for message chaining?

      Remember that another one of Apple's guidelines is to use fully-descriptive method names rather than ones that might be brief but not descriptive. Omitting the word "get" is a bit counter to that guideline and it's puzzling why they recommended it, especially when they have methods like: "initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:"

      I don't think that 3 extra characters on an accessor is really gonna break the bank in light of stuff like that! ;-)

      Like I said in another post, none of this replaces reading documentation or understanding the classes you are working with. This is all about triggering your memory while scanning through code. Conventions like using "get" and "set" just allow you to more quickly and easily recognize what your code is doing, i.e. self-documenting code.

    39. Re:Soem of the complaints aren't valid by Graff · · Score: 1

      Of course, I didn't mean that those were examples of state. I was just giving examples of getters that might do more than simply return the value of a field.

      I do agree that for a complicated function you definitely want to be verbose about what it's doing. The method name getRisk() implies that the method is simple, a name like calculateRisk() might be more appropriate for a more complex method - or even start going into names like calculateRiskByReferenceClassForecasting(). ;-)

    40. Re:Soem of the complaints aren't valid by Anonymous Coward · · Score: 0

      There are better ways to give advice than insulting the person while you do it.

      But giving advice without insults is called consulting and costs money.

      You seem to forget that consult comes from con and insult.

    41. Re:Soem of the complaints aren't valid by psydeshow · · Score: 1

      Nice. That's going on my wall.

    42. Re:Soem of the complaints aren't valid by TemporalBeing · · Score: 1

      and the use of java-style retarded naming conventions in c code is a source of both consternation and bugs.

      Uhh...CamelCase (and camelCase) naming conventions existed long before Java. And they do a lot better at minimizing bugs than hungarian notation, which does better than no indications whatsoever. Also, the longer variable names help quite well with reducing error when searching for the declarations and initializations. For example, using 'rate' might turn up:

      struct interestInfo
      {
      ...
      double rate;
      ...
      };
      ...
      struct amortizationInfo
      {
      ...
      int rate;
      ...
      };
      ...
      struct eFSA
      { // employee FSA plan info
      ...
      short int rate;
      ...
      };
      ...
      struct eRetire
      { // employee IRA or 401K plan info
      ...
      long int rate;
      ...
      };
      ...
      union accountingInfo
      {
      ...
      struct amortizationInfo amortization;
      struct interestInfo interest;
      struct eFSA fsa;
      struct eRetire retire;
      ...
      };
      ...

      Now which one will you be able to certainly count on being correctly accessed? You'll need to know a lot more about the program, etc.

      Note: I'm not saying the structuring naming above is good practice or not; but you'll likely find something like that in legacy programs that are being maintained. Especially programs written by "clever" programmers.

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    43. Re:Soem of the complaints aren't valid by badkarmadayaccount · · Score: 1

      typedef is your friend, most IDEs tooltip variable types.

      --
      I know tobacco is bad for you, so I smoke weed with crack.
    44. Re:Soem of the complaints aren't valid by Bigjeff5 · · Score: 1

      Yeah, but now you could re-write the whole program based on that one variable name!

      --
      Security is mostly a superstition... Avoiding danger is no safer in the long run than outright exposure. - Helen Keller
    45. Re:Soem of the complaints aren't valid by Bigjeff5 · · Score: 1

      That's how a nice IDE helps you out, once you've typed it once you can type a few characters and tab it. Microsoft has fantastic IDE's.

      Though, going from Visual Studio to a text editor makes you go "Ooooh snap...".

      --
      Security is mostly a superstition... Avoiding danger is no safer in the long run than outright exposure. - Helen Keller
    46. Re:Soem of the complaints aren't valid by Bigjeff5 · · Score: 1

      For example, cdate, mdate, adate (creation, modification, and access dates)

      Not being a C programmer from the dawn of the language, I had no idea what your arbitrary conventions meant until you qualified them. Is cdate an odd date you're using as a constant? Maybe you wrote an ActiveX that you for some strange reason call cdate, how am I to know? Maybe it calls the function to configure the date, I don't know!

      Is cdate really better than CreationDate when you can type cre-tab to fill it in? Especially since it is then impossible to mis-type it and create one of those bugs that only rarely surface and take hours of mind-numbing testing to track down? Seems I save a bit of coding time and an assload of clarity by just giving it a sensible name. obuff is particularly bad, is that an output buffer or did you set an object to use the buffalo class? Beats me.

      Maybe you only do your coding in plain vanilla C, but for everybody else those variable names are unreadable and difficult to maintain. Why do you demand I revert to the convention spec when there is no good reason for the convention to generate easy to read code?

      I dunno, maybe if I had decades of idiotic and completely arbitrary naming conventions behind me these meaningless variable names would be more useful to me.

       

      --
      Security is mostly a superstition... Avoiding danger is no safer in the long run than outright exposure. - Helen Keller
    47. Re:Soem of the complaints aren't valid by Mr2cents · · Score: 1

      erating is not fine. You can't just jump into the code and immediately deduce its meaning. It could be some sort of error. It could be something else. So you have to postpone making up what the variable is for and keep an open mind about it until you discover what it really means. Add a few of those together and you will have turned the average reader into a neurotic pile of misery. You wouldn't make up words like that in regular conversation, so don't do it in code either. Also, if it is part of an employee struct, the 'e' is completely redundant, and such redundancies are a bad thing. It's like violating the normal forms in database design.

      On a sidenote, when declaring variable names that are composed words, or when using pre-/suffixes (nothing against that, unless you're using system hungarian notation) I have become a fan of the underscore. Why? Because variable_name is more readable than variableName or any other capitulation scheme you can think of. You might think these are details, but when reading code, these little things add up quickly. And readability is *the* *key*.

      --
      "It's too bad that stupidity isn't painful." - Anton LaVey
  31. what? by Anonymous Coward · · Score: 0

    why do we call this 'clever'?
    clever as opposed to what, stupid?
    maybe 'obscure' would have been a better word...
    imho, the Linux Kernel Coding Style is the best.

  32. I may have to give up by some-old-geek · · Score: 1

    First, I suggest a perusal of Capers Jones' book Software Assessments, Benchmarks, and Best Practices, from which we learn that most of the cost of internally developed systems (the sort TFA is talking about) is in maintenance. So there should be no argument that making the code maintainable is of some high priority.

    [f/x: get off my lawn] Sadly, there are many programmers who don't understand that maintenance is not the act of rewriting the system in a language they would like on their resume. That might be adaptive maintenance, but the lion's share of maintenance actually involves fixing that which is broken (this would be corrective, perfective, and preventive maintenance).

    Sadly (again) we already know the answer to the OP's question. You need an enforcement mechanism. The cheap and easy way to implement that is via code reviews. And we know that isn't going to happen.

    Why? Because too many people who get to make decisions don't want to believe that first item from Jones' book. Making an innovative change to a UI is sexy, makes it obvious that some work has been done. Bullet-proofing user input edits is mundane, and smacks of cubicality.

    You are unlikely to get a commitment from management to let you do things "the right way." If you did, you would have no way of knowing that it won't be rescinded when the boss' kid gets a job programming in the cubicle next to you.

    The only way I know of to make this work is peer pressure. And that is unreliable. Thus maintenance will always have at least some aspect of the "fix what the clever kid did" to it.

  33. Coding style by tomhath · · Score: 1

    Coding style is a no brainer for most languages: Use the default that your IDE provides. Or lacking that, whatever the "prittyprinter" program produces. If someone violates the style convention, the IDE or pretty printer will clean it up. Design reviews, code reviews, and updated documentation are unquestionably good ideas but they have to be budgeted in at the start. A project manager who's afraid of missing a delivery will treat them as slack in the schedule and let them go even faster than they will squeeze the testing schedule (but that's another story).

    1. Re:Coding style by gbjbaanb · · Score: 1

      I kinda agree, I hate the coding styles documents (usually written by people who no longer, or never, wrote code according to the same documents!) that tell you how to program. Unfortunately, beautifiers have 1 problem in that they reformat your code and that can (in some cases) make reviewing differences between checked-in revisions difficult (so make sure you format your code to a single config before checkin).

      The best coding standards are:

      1. keep your style in keeping with the code you're changing.
      2. If writing new code, make the style the same as the majority of the existing codebase.

      The rest is just frippery, its pointless telling someone that they SHALL put 2 spaces between every if statement and the loop variable, or 3 blank lines WILL be placed between functions except when the function is a supporting helper that is closely associated with the next function, etc etc.

      Unfortunately the above standard doesn't come in 40-page documents, so management will consider it to be inferior. Sigh.

  34. author seems somewhat confused and inexperienced by bcrowell · · Score: 5, Informative

    The author of TFA seems somewhat confused and inexperienced.

    1. "Most of the variables in CRAP are one or two letters long. Originally, this was due to the memory constraints involved when programmers first designed and built the system." This is not particularly plausible. C is a compiled language, so using long variable names has no effect on the amount of memory used at run-time. It would also have been more or less a non-issue in terms of RAM used at compile-time. C only dates back to 1972, and didn't start to get popular until ca. 1980. By that time, using long variable names would have had a pretty negligible effect on RAM used by the compiler in proportion to total available RAM. And in any case, if compiles are taking too long, you just break up your files into smaller parts.
    2. He uses this code "for(ss = s->ss; ss; ss = ss->ss);" as an example of bad code: "For those of you that are interested, the line traverses a linked-list of sources and sub-sources to process the values inside. But it took a good deal of research to figure that out, because there were no comments and the variable names, well, suck." Well, I read that and said to myself, "It's traversing a linked list." I think what's really going on here is that the author is probably a programmer who learned to program relatively recently with C++ and Java (he says in TFA that those are the languages he's used to), and he's used to doing things with big OOP libraries. The culture he's been inculcated in is one in which you never have to understand how a linked list is actually implemented, because you just use a library for it. To anyone who's actually implemented a linked list in a language that uses pointers, it is fairly obvious what this code does. It shouldn't take "a good deal of research" to figure it out.
  35. Linked list by tylersoze · · Score: 1

    for(ss = s->ss; ss; ss = ss->ss);

    Really? An idiomatic linked list traversal is too hard to understand? Does this guy think find postfix increment (++) too confusing too?

    I admit though it is confusing if the semicolon at the end isn't a typo. Is this straight C or C++? I can't imagine that statement actually doing anything useful unless there's some kind of C++ operator overloading going.

    1. Re:Linked list by TheSunborn · · Score: 3, Insightful

      While I don't understand why he did have a problem with seeing that this is a linked list traversel, I think he do have a point about fucked up naming, because in what implementation would you call the node to the next element ss instead of next, or nextNode.

    2. Re:Linked list by Anonymous Coward · · Score: 0

      I had the same thought as you - that line of code did not seem terribly opaque. But I think there is an understandability issue here. "s" and "ss" are just painful variable names, especially when ss is also a field. The over use of s's obscures what (I think) is going on here, which is that "s" is a struct containing a linked list "ss", which is then walked over. It is not really even clear to me whether "s" and "ss" have the same type. Is "s" a linked list, and this traversal is skipping the first element? Or is "ss" a list element of "s", which we are then iterating over? For me, most of the confusion comes in the initializer statement. The rest, as you say, is an idiomatic traversal.

      Of course, using Java-style idioms does not make this line much better:

      for (ss = s.getNext(); ss != null; ss = ss.getNext())

      Although here it is clear that I've gone with the "s is itself a list and we're skipping the first element" approach, rather than:

      for (ss = s.getList(); ss != null; ss = ss.getNext())

      Of course, the verbosity here is unpalatable... if we go with next() instead of getNext(), it's far better, IMO.

      Finally,

      I admit though it is confusing if the semicolon at the end isn't a typo. Is this straight C or C++? I can't imagine that statement actually doing anything useful unless there's some kind of C++ operator overloading going.

      I think he was just trying to show the loop conditions, and not the body.

      That said, I *despise* operator overloading for precisely the reason you indicated: it is impossible to tell what any given statement is doing because your basic, built-in operators can do bizarrely different things! To build on examples you've given, with C++ iterators, the postfix increment "ss++" now means "ss=ss->ss"! Madness!

    3. Re:Linked list by IDK · · Score: 1

      The code finds the last element in a linked list...
      Isn't that useful?

      For example concat:
      void concat(s,x){
        for(ss = s->ss; ss; ss = ss->ss);
        s->ss = x;
      }

      Although as the article describes it, the semicolon is a typo...

    4. Re:Linked list by Anonymous Coward · · Score: 0

      I've seen that anti-idiom ("ss" being the next element of "s") in production code, and I could not agree with you more - it is seriously fucked. It completely obscures what's going on.

      In the particular case I'm thinking of, that idiom actually obscured a serious bug, which illustrates another danger of "clever" code: it is so clever that it is not obvious that it is wrong.

      In my line of work I fight this battle over and over again. They write code seems clever, turns out to be wrong, and is left for me to fix when subtle bugs appear. This, even though I work with fairly smart people. Hell, perhaps it's *because* I'm working with smart people. I just happen to be smart *and* careful ;-).

    5. Re:Linked list by fredrik70 · · Score: 1

      ... it traverses the list nd then ends when itself is set to null, great, now we don't know where that last node is anymore.
      oh, and s is still pointing to the b eginning of list so you screwed the ehole list now by setting it's ss param to x.
      maybe this would work:

      void concat(s, x)
      {
            var prev;
            for(ss=s->ss, prev=s; ss; prev=ss, ss=ss->ss) ;

            prev->ss = x;
      }

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    6. Re:Linked list by tylersoze · · Score: 1

      Maybe I'm just being slow this morning but I still don't see how that loop is doing anything useful in the code you posted. The only effect of that loop is to increment the ss pointer which isn't used after that. It looks like that code is just setting x to be the next element of the variable s you just passed in.

      You probably meant to stop the iteration at ss->ss == NULL then set ss->ss = x

      I think this shows implementing linked lists is error prone regardless and use libraries of those features if available and don't reinvent the wheel if at all possible :)

    7. Re:Linked list by ysth · · Score: 2, Informative

      That doesn't seem to be the case here; s is a "source", s->ss is the source's list of "sub-sources". So the s and ss names are just accurate abbreviations, not an example of your "x" and "xx" phenomenon. The "next" pointer for a sub-source itself being named "ss" is a little strange though.

    8. Re:Linked list by Anonymous Coward · · Score: 0

      in the context of lists it's not too hard to understand; if you've got a list it's quite common to refer to it as x:xs where x is the head and xs is the rest of the list (with : being the cons operator)

    9. Re:Linked list by greg1104 · · Score: 1

      The point is that had the variables been given useful names, what the idiom accomplished would have been obvious even to someone seeing it for the first time. For example, if we take that code:

      for(ss = s->ss; ss; ss = ss->ss)

      And rename its variables to not be retarded:

      for(node = head->next; node; node = node->next)

      Then not only would a newbie coder likely recognize what the code was doing, they'd have learned a useful C idiom through code reading even if they're new enough to that language to not have known it already.

    10. Re:Linked list by Anonymous Coward · · Score: 1, Informative

      When the nodes contain multiple next pointers as they are stored in multiple lists/graphs so you need to know what list next is being traversed. So a simple 'next' is no good. Or m_pNext or anything

      Regardless it's really obvious what the code does - it sets ss to a null pointer. Even without that semi-colon at the end I spent a few minutes scratching my head, thinking I was missing something because the code was so clear in it's purpose.

      Actually, the short variable names make it really clear to spot what everything is doing in that context simply because they are so short, mentally digesting the statement is trivial.

    11. Re:Linked list by Anonymous Coward · · Score: 1, Informative

      TFA says that the list in question refers to source (s) and sub-source (ss)

    12. Re:Linked list by zippthorne · · Score: 1

      For efficiency reasons, the programmer may have remapped the letters and numbers, swapping one or more rows.

      --
      Can you be Even More Awesome?!
  36. Re:Some of the complaints aren't valid by tomhudson · · Score: 1, Insightful
    And this hooter:

    The other side of C/C++ indirection is pointer logic. Pointers are powerful, but dangerous. For now I will just say try to stay away from statements like:

    int ***values;

    Instead, try C++'s STL Containers . First, the code is in C, not C++. Have fun porting the STL.

    Second, there's nothing wrong with int *** values; If you can;t figure it out, go back to java.

    and .. "OMG USE BRACKETS ALL THE TIME"

    if(test)
    do_something()

    to

    if(test)
    do_something()
    do_something_else()

    People get bitten by that once, then they learn. No brackets means a SINGLE statement. Brackets are optional, and not needed. Don't lcutter up your code because some n00b doesn't know how to read.

    I've seen people get bitten because they put brackets in - and because their indent style isn't consistent (they used 4 spaces instead of a hard tab, so when they cut-n-pasted code, "BAD THINGS(TM)" happened.

    Sure enough, the author cites Java coding conventions at the bottom of the article. c is NOT java. java is way to verbose, some of us like the clean lines of c, and think java should at least get a pre-processor so we can hide some of the typographical pollution. Even the original creator admits that the "everything is a class" model was a bad idea.

  37. Too MUCH of this by omb · · Score: 2, Insightful

    There is increasingly a meme that pretty code in a strongly typed language id OK, everything else is CRAP.

    Well no, neatly written code, in whatever, is good, as are good code and clear comments where they are needed, ie NOT,

    i = i++; //increment i

    Some of the worst code I have seen written is in C++, Java and C#. OO over the top, full of OO jargon, code that wanders around a thousand method calls without solving the problem, and TOO MUCH CODE, zillions of complex libraries and dependancies.

    Clarity, order and simplicity are the secret of writing good code, not language, tools or methodologies, and then it can be written in anything from Lisp to C#.

    1. Re:Too MUCH of this by Anonymous Coward · · Score: 1, Insightful

      i = i++; //increment i

      That code does not increment i. It's undefined. Depending on the implementation, it might increment i, leave i the same, or print out "forty-two" and abort.

    2. Re:Too MUCH of this by Krahar · · Score: 1

      Some of the worst code I have seen written is in C++, Java and C#. OO over the top, full of OO jargon, code that wanders around a thousand method calls without solving the problem, and TOO MUCH CODE, zillions of complex libraries and dependancies.

      Code that "wanders without solving the problem" is a direct consequence of writing cohesive classes that solve one problem and delegates everything it isn't responsible for. The point to appreciate such a thing is to consider the abstractions involved as the basic concepts with which to think about the program. This is an acquired skill. If you view a debug trace as the basic tool to understand your program, you will have a hard time, and that seems to be the basis of your frustration.

    3. Re:Too MUCH of this by Anonymous Coward · · Score: 0

      That code does not increment i.

      I'd like to credit you with an attempt at humor, but I highly doubt it.

    4. Re:Too MUCH of this by Anonymous Coward · · Score: 0

      > That code does not increment i.

      It surely does.

      Maybe you should actually compile and run it before you share your 'wisdom'!

    5. Re:Too MUCH of this by Anonymous Coward · · Score: 0

      >> That code does not increment i.
      >It surely does.
      >Maybe you should actually compile and run it before you share your 'wisdom'!

      Same AC here - sorry for the insolence, I stand corrected. But you should have said it is "not guaranteed to increment i." Some compilers it does, others it doesn't. On mine it does, YMMV.

    6. Re:Too MUCH of this by Anonymous Coward · · Score: 0

      I hope you realize that i = i++; is just bad code. The ++ operator has a self-storage function to it. i++ means i = i+1; You do not need the i = in front. It is just i++;

  38. keep it simply stated by God+of+Lemmings · · Score: 1

    Our workplace is such that everything has to be easy to follow and understandable with a glance. This is not necessarily because someone else will be working on our code so much as that we almost certainly end up coming back to it 6-12 months later, or that the person writing it won't be the person maintaining it or porting it.

    If it isn't easy to follow, you can usually fix this by spreading out the code and inserting more comments, and avoiding shorthand statements like inline ternary that save typing, but don't enhance readability. Inline comments are uncommon, instead varying kinds of flower-boxes before a section of code. In general, it ends up that being clever requires much more commenting in the flower box to explain functionality, so in the end it becomes a wasted effort.

    A few days ago I saw someone going around with this sig from Brian Kernighan;
    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

    --
    Non sequitur: Your facts are uncoordinated.
  39. Teams by jlowery · · Score: 5, Insightful

    I've worked with teams a large percentage of (supposedly) hotshot programmers, and on teams with a similar percentage of mediocre talent. In my experience, it is the team with the so-so developers that deliver the more maintainable code. Why? I think it's because they know their limitations and are not afraid to "talk out the process" of writing code. They ask for feedback and opinion.

    What that leads to is a collaborative development process, where everyone has some idea of what the other is doing. And in these environments, for some reason, people take ownership and responsibility for their code, end-to-end.

    Contrast that with the hotshot teams: they know too much to ask for help, resent questioning of their implementation, mess around in other peoples domain "because they know better", and engage in heated arguments over trivial or religious matters. And in the final analysis, the lack of cooperation leads to disfunctional interfaces between components, idiosyncratic code, and incomplete functionality or low-quality performance.

    Whereas the so-so teams learn to collaborate to get things done, the hotshot teams rely on heroics: they take on too much, show exaggerated progress by declaring their code complete even though it fails edge cases, and then spend outrageous overtime fixing 'bugs' (or worse, they're too important to work on bugs, they do features, so the lesser mortals on the team get to clean up after them). Because bug fixing doesn't get scheduled up front, the schedule slides and more work hours are demanded to catch up (with decreasing effect).

    To my mind, the MAIN criteria for arriving at a maintainable codebase is OWNERSHIP, OPENNESS, and COLLABORATION. A collaborative team can do more in 40 hours than a heroic team can do in 60. They just don't look so impressive.

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

      I used to work with someone who thought in the hotshot way you describe. The additional caveat to him was that, when he found something he didn't like in your code, the commit comment was something along the lines of "WTF is this s**t, fix it now." Now I work in a team in the opposite camp. On the one hand, I'd say that his method, while very irritating and prone to error, would push one do a certain amount of work per day (i.e. - a lot of it). The opposite is somewhat more relaxed and, while it leads to somewhat less buggy code, it also seems to lead to more lax standards in code. It's a tough line to follow; be skilled and care enough to put out good code yet humble enough to ask for help when you need it. Ideally, if there were trust among the team members (people forget how to do stuff sometimes; admit to it) and agreement, everything would be ideal. Ah well.

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

      From your description, whats clear to me is than neither the hotshot neither the so-so are professional programmers. Professional programmers (I prefer the term developer or software engineer, because I think that writing programs is more than write code against a specification) are very hard to find.

    3. Re:Teams by thethibs · · Score: 1

      You really should make up your mind. Are they 'hotshots' or incompetent. You can't have it both ways.

      --
      I'm a Programmer. That's one level above Software Engineer and one level below Engineer.
  40. While I'm not an expert developer.... by MrCrassic · · Score: 1

    The one job that I did have as one made me realize exactly how uncommon it is in corporate-level work to find code with nice, detailed comments describing what's going on where. I will blame the lack of comments for one project I was assigned taking months to complete rather than weeks or days, especially considering that it was pure Java Swing code (i.e. no NetBeans), which is especially infuriating to work with.

  41. Learn from the masters by deblau · · Score: 1
    --
    This post expresses my opinion, not that of my employer. And yes, IAAL.
    1. Re:Learn from the masters by jocabergs · · Score: 0

      Good article, I concur with most of it. I don't mind "hotshot" coding, so long as its well commented out, so us non "hotshots" have a clue. Being clever can be a really good thing, just have to make sure that everyone is on the same page if someone else is going to be accessing, altering, updating the code later including yourself, nothing worse than being too clever, then going back to it at a later dumber stage of your life...

  42. Code Review is only part of the solution. by TimCostantino · · Score: 1

    Changing someones development practices is a kin to changing any other behavior, I.E. hard to do.

    I've found that code reviews offer a good barometer of where everyone is on the behavior chart but it is not enough to make a significant change to the behavior.

    Here are few items that I find essential:
    1) Maintainability Must be a priority: The architect\tech lead on the project must make this a priority. Simple code must be reinforced at all stages of development. This means new development must wait for previous development to be refactored into simpler code.

    2) Shared understanding: The team MUST recognize the importance of this requirement. If they don't then the constant reinforcement will seem more like nagging, nit-picking than anything else. Have the entire team read "Clean Code" send out the Daily WTF articles. Jokingly pass out the bad code offsets.

    3) One on One Coaching: Often complicated code is written simply because the simpler solution was not obvious. To help overcome this, team members should help each other with refactoring efforts. As an example: Interfaces and factories are often seen as "To complex to be simple" by junior developers. Consequently, it is the responsibility of the entire team to help teach why these "more complicated" solutions are actually much simpler and cleaner than the alternative.

    4) Constant Communication: As with all creative work, whether you've accomplished the goal is very subjective. This means the team must have constant discussion, and sometimes debates, on what is maintainable. If you are the tech lead, be sure to show examples of your own code that is sub-par, and then discuss how it can be improved. If you don't have samples of sub-par code, you need to start writing more code. I can't emphasize enough that the tech lead must use their own bad code as examples, this helps create an open environment where people feel free to make mistakes and ultimately learn how to write better code.

    Well that's my two cents as I sit here getting ready for Football to start. (c:

  43. Test Driven Development by ixl · · Score: 1

    TDD, TDD, and more TDD. If it's too clever to maintain, than it's not testable. When done properly, test driven development functions very well as a guard against that sort of thing. The converse is also true, by the way. If something is very clever, but written in a testable way, than it's likely to be maintainable and easy to read. Even if it's not easy to read, the tests allow it to be refactored into an easy to read form without breaking anything.

  44. Perl Critic by Herkum01 · · Score: 1

    Perl has probably got one of the best coding analytic suites in Perl::Critic. It addresses numerous areas dealing with Best Practices and addresses certain types of bugs. It is also highly configurable and easy to write your own rules as well.

    The hardest part was actually getting people to use it. The fact is, there are a lot of people who have a ego and rather inflexible about changing their habits. The other side of the business will not care unless it can be shown it is a common practice or directly impacts money. So it is a tough battle to fight and most people are just not willing to get involved with it.

  45. I wrote my own platform by holophrastic · · Score: 1

    ...for web development. And the primary goal of this platorm is to make doing typical things very straightforward, and easy-to-do-right and hard-to-do-differently. Commenting teh code itself is completely useless because the code reads fluidly. So comments are limited to what isn't programmed, or what has been removed for good reason.

    Some advantages are quite clear when it comes to security things like user permissions and sql injection avoidance. The platform makes it horribly difficult to do those kinds of things in the traditional way, and really easy to do it in the consistent way.

    So the rule really is that if it's difficult to write, and it looks like carp when you're done, then there is a proper way to do it.

    It's what a friend of mine has been saying for years. It's not enough to make good code look good. You've got to make bad code look bad.

  46. Code != documentation by mveloso · · Score: 4, Insightful

    As I've explained many times at work, code is not documentation.

    Code only tells you what it does. It doesn't say why it was done that way...and the "why is it doing this" is really almost always the problem.

    1. Re:Code != documentation by julesh · · Score: 1

      As I've explained many times at work, code is not documentation.

      Code only tells you what it does. It doesn't say why it was done that way...and the "why is it doing this" is really almost always the problem.

      This is a very good point, and one that's often overlooked. I've seen people say that "no comments" is a good coding standard to work to: if your code needs comments to be understandable, they reason, it is too complicated. Good code can be understood without them. Simplify it. I think these people are on the right track but have missed the point somewhat: the coding standard should say something along the lines of "comments are not allowed to explain what something is doing; they should only ever explain why, because what is being done should be obvious from method and variable names and from the code itself."

  47. Treat comment bugs like code bugs by presidenteloco · · Score: 2, Insightful

    They are just as serious. Updating/"maintaining" a piece of code and not updating the comment
    should be made into close to a firing offense, after the suitable number of admonitions.

    The biggest weakness I find with code I review is that the programmers seem to be either
    inarticulate, lazy, smug, or exhibiting Aspergers syndrome (lack of empathy), in that they forget to
    include the most important comment for any method or class;

    The "What the h*ll is this?" comment that explains the gist of the method/class and why and
    in what contexts one should care about it.

    Also frequently missing is the considerate: "Mind the low headroom" comment.

    --

    Where are we going and why are we in a handbasket?
  48. And your definition of "clever" is? by mi · · Score: 1

    Simple, clever doesn't pay the bills, reliable and maintainable do.

    Except that one's "clever" is another one's "perfectly normal". For example, a client I worked for, had a huge body of C-code, where they — following one of the company founders' coding practices — would bzero a just calloc-ed array. In hundreds of places throughout the code...

    Was it clever of me to not do it, knowing that calloc returns zeroed-out memory (its only difference with malloc in these days of flat memory), or was it stupid of them to insist on doing it for the sake of "reliable and maintainable" code?

    --
    In Soviet Washington the swamp drains you.
    1. Re:And your definition of "clever" is? by pem · · Score: 1
      Arguably, it would be stupid of you to assume that this was done because somebody at the company didn't read the documentation, rather than because some ancient C compiler vendor didn't read the documentation and this bit one of the programmers at the company.

      Also arguably, it would be stupid of you to not to follow the existing conventions, regardless of how stupid they are.

      But it probably wouldn't be stupid to gently point out that all the calls to calloc/bzero could be replaced with a macro invocation, which on most platforms could have the bzero removed, and then the bzero could be ifdefed back in if there is still call for the thing to run on a broken compiler...

    2. Re:And your definition of "clever" is? by mi · · Score: 1

      it would be stupid of you to not to follow the existing conventions, regardless of how stupid they are.

      This — following existing conventions regardless of how stupid they are — is exactly how groups of people (including corporations) stagnate and then die out...

      [...] call for the thing to run on a broken compiler

      Except, no such compiler exists (nor ever existed) and another one of the company's old-timers confirmed to me, that the guy, whose example the rest of the company were following, was, indeed, ignorant of this feature of calloc...

      It didn't matter much in the great scheme of things — their code was so bad, they didn't even dare to compile it with -O... But, hey, it was consistent, so it paid the bills, right?

      --
      In Soviet Washington the swamp drains you.
    3. Re:And your definition of "clever" is? by coryking · · Score: 1

      knowing that calloc returns zeroed-out memory

      The founder probably did this because back in the day he ran across some compiler with some bug that didn't always zero out the memory. That or he knew somebody who knew of a compiler that didn't always zero out the memory.

      In my opinion, a lot of "optimizations" are really just programming urban legends. Somebody knew somebody who knew a guy who wrote the documentation for a compiler said that you should always bzero your calloc-ed memory. Somebody heard from somebody next to them in an airplane say that their brother works for Borland and you should always change x = x +1 into x++;. Then somebody else will mention their sisters cousin heard from a friend that it should really be ++x;. C seems notorious for this because a lot of these rumors were probably once true and are still passed down as gospel from people who worked on them (or knew somebody who did).

      In other words, I take pretty much all of these "tricks" with a huge grain of salt. Until you show me the numbers, it is all rumor. Even then, if it makes the code hard to read and it isn't in a critical path (hint: 99.9% chance it is not), I dont care anyway--readability trumps everything.

      The smartest words I ever heard about this are "If your compiler can't figure out what you meant and optimize it, get a new compiler". Good words to live by.

    4. Re:And your definition of "clever" is? by mi · · Score: 1

      Well, my point was, "clever" is in the eyes of the beholder...

      I'd add, that the whole usage of the word while adding negative connotations to it, such as: "Clever does not pay the bills," — is rather offensive. Unfortunately, it is wide-spread...

      And typically it goes like this: I didn't think of that, the guy must be clever (a.k.a. smart-ass). Maybe, one actually has to be smart and clever to be offended by it...

      --
      In Soviet Washington the swamp drains you.
    5. Re:And your definition of "clever" is? by Steeltoe · · Score: 1

      And while you're cleverly thinking about all this, the other guys have just finished another product for you to maintain. Horrible code too, but the customer bought it and now it needs to be maintained and upgraded, until it becomes a horrible spagghetti monster - and you start all over again with fresh code (but now YOU're on the team coding new things, and have such a deadline, you forget all your ramblings of "best practices", and just make some code that finally works).. You're not proud, you left that years ago, but you get paid.

      He he.. why I left "IT"..

    6. Re:And your definition of "clever" is? by wisty · · Score: 1

      "Clever", "obvious" and "maintainable" is always in the eye of the maintainer. If your goal is to write code that can be maintained by the next guy, there is one simple way to end all the arguments:

      Have someone else read it.

      Nobody has a clue whether their code is good or bad. Everyone's opinion of their own code (like their opinion of their own BO, looks, karaoke ability, sense of humor, and driving skills) is ridiculously overblown. Except for the people who lack confidence, and think that they suck no-matter how good they are.

      If you want an unbiased opinion, get one. Code reviews are essential.

      Of course, some companies don't have the time or resources to do code reviews. If that is the case, they should just stop pretending that they will ever write maintainable code, and just abandon coding standards completely.

    7. Re:And your definition of "clever" is? by mi · · Score: 1

      Have someone else read it.

      In the particular example, nay class of examples I've given, that would mean dumbing the code down, so that the weakest programmer in the company can understand it. That could mean severe pessimization overall: "Why don't you leave those bzeros alone, so that it is obvious, the memory is cleared?"

      Code reviews are essential.

      I agree with you on this one. But it will not solve the problem of "clever" being relative...

      --
      In Soviet Washington the swamp drains you.
    8. Re:And your definition of "clever" is? by Bigjeff5 · · Score: 1

      But, hey, it was consistent, so it paid the bills, right?

      Well, you did get paid, right?

      If a manager thinks he knows better than the guys he hired to do the work, you're never going to win. This is true for everything. If it bugs you that much to bzero calloc then find a new company to work for.

      --
      Security is mostly a superstition... Avoiding danger is no safer in the long run than outright exposure. - Helen Keller
    9. Re:And your definition of "clever" is? by wisty · · Score: 1

      If your weakest programmer can't understand those bzeros (even after you've explained it in the review), then a few bzeros are the least of your worries.

  49. I've never had an enjoyable experience with this.. by Anonymous Coward · · Score: 0

    One company I worked at, when we sat down to discuss basic coding standards at the start of the project one of the developers whined and whined and wouldn't give up on one very stupid point. He was in his 60s and he claimed that he had used 2 spaces instead of 4 his whole life because it fit better on dot matrix printer paper. We pointed out that 2 spaces looks less readable and 4 looked fine on todays printers and fonts. He wouldn't give up and it was prolonging the start of the project indefinitely to the point where management said fine just use 2 then. So, we were all stuck using 2 spaces, which led to a giant war during development. We were all using Eclipse, so anytime he would write a piece of code with 2 spaces, the rest of us would would click Format document and cause all his 2 spaces to turn to 4 automatically and then re-commit. Which would make him cry, while the rest of us laughed. Essentially, majority won, but thank god for auto-format otherwise we wouldn't have been able to stay sane at that job.

    Therefore, it is my opinion, that coding standards are crap. And, the only coding standard you need is to abide by whatever auto-formatting that Eclipse or your preferred IDE provides. As far as working out concepts like modularity and that sort of thing, simply refer to refactoring rules in design patterns and you'll do great. Enough said, now get coding and stop wasting time discussing nonsense.

  50. Testability by cmsjr · · Score: 1

    While coding style is certainly important, the most clearly written, nicely commented, richly documented source possible can't tell you if the code does what it's intended to. Formal coding standards may help mitigate the difficulty of debugging and modifying a program, but I think can you get a lot more bang for your buck by implementing a solid testing framework. If I had to pick between coding behind someone with great style, or someone with great unit tests, I'd take the latter.

  51. Names, meanings, code documentation & culture by Anonymous Coward · · Score: 0

    Meaning is very problematic beast. Philosophers has know already for few centuries how difficult it is to define proper names and point how meaning is bound to words or other constructs. If I have understood some what modern day consensus of philosophers any language will always be more or less defined for small audiences. To say that in practical way tech talk is talked by techies to techies. So called general language that can be heard in news or such will not cut, it just lacks practical way of saying difficult things e.g. news for nerds are not written same way as CNN articles.

    Where does that lead us? Code documentation, style and even variable names can be meaningful and sensible activity, but only within limits of programming culture. It is waste of time to teach non programmers to understand 'this particular' code. Non programmers should first learn programming culture and then they should be able to understand. I understand many of you will say that there is no such thing as homogenous programming culture. In that you are absolutely right, and wrong. For example intending code is better than not intending, but we can argue till end of time is correct intend 4 or 8 chars. Programming languages have idiomatic expressions, one should always favor them. This sort of 'rules' are part of culture. But culture is greater construct than set or rules. In order to understand variable names for example one has to take a look of hackers dictionary (foo, bar, zyxxy...). Some times there are references to geek popular culture (I've seen magical number 42 too often that it would be just a coincident).

    Defining coding practices is a very difficult task. The definition should match with culture and limit possibilities provided by culture. Paradoxes are hard to crack.

  52. elegant != clever by dsoltesz · · Score: 4, Insightful

    Elegant and clever are not the same thing.

    Elegant describes the algorithm or solution as using resources efficiently, having no unnecessary steps in getting to the solution, and easily readable to another programmer familiar with the subject at hand (as AB3A mentioned inre to DSP).

    Yes, if we use Webster's definition, there is a certain amount of "cleverness" in beautiful, elegant code. However, when we say "clever" we usually mean cutesy-clever, like mashing several traditional lines of code into a one-liner. That's fine for a geeky contest of "who can write this using the fewest number of characters," but (as most of us agree) does not have a place in professional code. One-liners and similar stunts might be clever, but are rarely elegant, and cause headaches for later maintainers of the code.

    1. Re:elegant != clever by bXTr · · Score: 1

      Exactly.

      I've read too many comments where people deride 'cleverness' as if they don't want their programmers to think and the ones that can and do are bad programmers. It all seems like overcompensation by the PHBs for the glut of programmers that came in during the DotCom era out of Community College or a Programming for Dummies book. Programmers became a commodity, and the level of ability, knowledge and expertise dropped accordingly. Managers dealt with it by making this the norm and making it a crime to be a smart programmer.

      Up-to-date documentation and well-commented code is good. Code clarity is also good. That is not in dispute, but that has always been the case. This is all about accommodating the off-the-shelf programmer at the expense of the ones with experience and know-how.

      --
      It's a very dark ride.
    2. Re:elegant != clever by Anonymous Coward · · Score: 0

      I don't think my definition of elegant is the same as yours, but apparently using a dictionary to argue the point is won't be a workable solution.

  53. A fool's errand by ClosedSource · · Score: 4, Insightful

    After you've been in this business for more than 20 years without giving it up to become a manager or guru, you may find that coding practices are orthogonal to code quality.

    Just do the best you can with the cards you've been given.

    1. Re:A fool's errand by Jaime2 · · Score: 1

      I'm so happy to hear someone else say this. Some of the worst code I've seen in my life was 100% up to the "coding standards" it was written under.

      I've seen many examples of development teams that write the most unmaintainable heaps of crap, but they are very good at variable naming conventions. I my opinion, elaborate variable naming standards should only be established after getting the basics covered. Instead of berating the new guy for not using some stupid prefix, get on him for poor commenting or source control practices. My biggest personal pet peeve is people who don't understand what they are checking in. I constantly get temp files, unrelated and abandoned attempted fixes, bread crumbs debugging, and irrelevant config changes checked in with whatever the developer was actually trying to check in.

  54. Old comments are good by Anonymous Coward · · Score: 0

    I worked on some code where there was a comment from a few revisions before. I believe people who comment their code usually create better code then the people who don't comment or who don't update comments. The code and the comment were out of sync and now there was a problem. After reading the old comments I realized that whoever updated the code didn't understand the general design the original author had intended. I changed the code to correspond to the comment and the bug was fixed. The old comment saved me a headache. I comment regardless of "official" practices because I know months or years from now I might be the person trying to fix some code I wrote. With the turnover in software and software teams these days people don't believe they'll have to fix their own code and hence think they'll be able to keep everything in their mind until the next job. Maybe it's to save time but the same practice of typing less would be better practiced by taking your hands off the keyboard for a second and thinking about writing maintainable code. If people are going to cut and paste then change a few things to make it quite clear what they should cut and paste. If you are doing some boilerplate stuff that you know people try to turn into some generic thing change the variable names in all the versions of your boilerplate stuff. They won't notice the code is very similar and they'll actually take a second to understand the basic boilerplate design instead of cutting and pasting it. Push the sophisticated stuff in a super class and put the simpler stuff in subclasses. People who create a subclass at a drop of a hat won't be creating a mess that is hard to fix. Enforce conventions by putting in code that does. Put in a comment that says the code will explode without it. People who understand will laugh at the comment and the ones who don't know better won't dare take the code out. Make it easy to do the right thing and make it hard to do the wrong thing. Sounds like a nasty bunch of tricks but I've gotten numerous comments about how easy my code is to maintain. Too many and if I wasn't fighting managers to help "fix someone's code" I probably wouldn't be writing new code.

  55. It's all Zen by furball · · Score: 1

    1k of code is simple in general to maintain. It probably has less bugs than 2k of code. It follows then that 999 bytes of code is simpler and probably has less probably of bugs than 1k of code. If you work with the logic, you arrive at the fact that if you write no code that is the simplest and most bug free version of anything you'll ever have.

    Have you ever heard of a zero-day exploit to a peace of software that hasn't been written? Didn't think so!

    Software development is really the domain of Zen monks.

  56. document interfaces, not code, and learn from bugs by jkajala · · Score: 1

    One of guidelines I have found useful is that document interfaces as much and detailed as possible, but if you feel you should write a comment in implementation think twice if the implementation is too complicated, or maybe there is some problem with the design. Does the function do straightforward well-defined task? If the function gets too long or complicated maybe there are some independent well-defined tasks that should be own functions instead of part in the implementation. Write so clean code that it doesn't shout need for any documentation. One other useful guideline: Learn from bugs and improve code quality from the bugs. Always when encountering a bug, not only fix the bug but also ask "How could I prevented this in the first place?". That gives important hints about the quality issues in the code. Maybe you are not checking your assumptions/pre-conditions/post-conditions/variants enough. Maybe interface of that function was not well-defined. Maybe there was a test case missing. Maybe something else was wrong. Study the bug and make sure similar situation does not happen again.

  57. Superiority of mediocrity by michaelmalak · · Score: 3, Interesting
    Abstraction and locality are conflicting forces.

    A "hotshot" programmer will aggressively abstract. A mediocre programmer -- one who keeps his nose to the grindstone and is ever mindful of deadlines -- is more likely to "inline" constants (i.e. not abstract them at all) or even repetitive blocks of code. When ccde and constants are "inline", code is much easier to read because you're not constantly looking up in other files what the abstractions are.

    Supposedly, both abstraction and locality aid maintenance.

    The truly master programmer balances abstraction with locality. And takes into account who will be maintaining and the expected lifespand of the code. If the code is to be retired in two years, why bother abstracting? The general rule of thumb is that abstracted code has to be utilized six times in order to make the investment worthwhile.

    When it comes to abstraction, the master programmer abides by the words of the Federation President, "Let us redefine progress to mean that just because we can do a thing, it does not necessarily mean we must do that thing."

    1. Re:Superiority of mediocrity by digsbo · · Score: 1

      Some good points.

      Both of these approaches (locality and abstraction) fail frequently. The inlining/cut&paste approach to locality I don't need to explain.

      Where the abstractions fail (and I see this more and more) is when the hot shot abstracts out the lower-level "dumb" classes but also mixes in assumptions about how they'll be used by the higher-level classes.

      What you end up with is a rigid, inflexible, unmodifiable framework that forces the user (i.e. the programmer extending or re-using the framework code) to build the application the same way the original programmer did. I mean to the extent that the "abstracted" configuration class has to be used so you can use some element of the application framework, which means you also need to pull in the framework's persistence model, etc., etc...

      The six-times reuse is much easier to achieve when you provide truly clean abstractions in the framework which promote reusing a small piece of the the framework without forcing the whole thing down the user's throat. It's much better since someone on a tight deadline can use what he needs, get the reuse, and maybe come back later for more.

    2. Re:Superiority of mediocrity by Anonymous Coward · · Score: 0

      If the code is to be retired in two years, why bother abstracting?

      Simply because, everywhere I've ever been where I wasn't the one having dictatorial control of such code's lifetime, that code will still be in service 10 years later, with all sorts of modifications for new requirements. And the management will still be saying, "We're replacing all this 6 quarters from now."

      - T

    3. Re:Superiority of mediocrity by Anonymous Coward · · Score: 0

      If the code is to be retired in two years, why bother abstracting?

      Because in four months time the Steering Committee will put the retirement project on hold pending the outcome of a Regulatory Review Panel who never reach a Consensus and the Project Team is repurposed to an Operational Support Team who spend the next decade cursing the original Project Team for not their shortsighted development techniques.

  58. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 1, Interesting

    Exactly! Mod this please. Anyone who has any knowledge of pointers will look at that loop and know what it is doing right away. The only exception is if you never learned pointers and just used the library function calls. That's what you get when you initially teach people such an abstracted high-level language (e.g., mega overhead JAVA). If you aren't going to use huge lists, there is no reason to include the overhead of the STL library (or any other); just form your own linked list (as done in the example)! Saves RAM, CPU and typing time. Also, it's 100% easier to prove correct mathematically (on paper). Try doing that with verbose library calls!

  59. Oblig by Anonymous Coward · · Score: 0

    ...manageable practices that ultimately offer a lot of value to the next programmer down the line who will have to maintain the code.

    Simple: Use Python ;)

    *ducks*

  60. It all starts with Documentation by CAOgdin · · Score: 1

    I've proven to my clients, time-after-time, for more than half a century, that programming is done BACKWARDS from good practice: We write code (maybe with comments), then we go back and document it.

    Instead of some vague specification, we need to start with DOCUMENTATION. We need to write the first draft of the user manual (or, in modular programming, the programmer's reference) BEFORE a line of code is written. That document must be reviewed and amended until all (or a good representative sample of) the "consumers" of that software are satisfied with how it will work. (For example, Windows is NEVER reviewed by real end users in simulation or documentation, so we get the persistent and buggy output of Redmond's programmers.) AFTER we know what we're trying to achieve, we can write requisite code to achieve those results.

    Yes, I know that's heresy...but it's the ENGINEERING way to do the job.

  61. STL not always a good choice by Anonymous Coward · · Score: 0

    NASA, I'm sure, writes many things that must run in real time. Unfortunately, STL is not always a good thing to use in this scenario. My company actually has a coding standard to never use STL in code that is run in real time. So why is that? Let's say you're doing a vector.clear() operation. In the most common linux implementations, the .clear() function does not deallocate memory. However, that behavior is not in the C++ STL standard. If I recall correctly, only the interface is defined. What's going on underneath is omitted from the standard. So here's an issue we had in one of our real time systems. We were running VxWorks and a certain process was taking significantly longer on VxWorks than it did in linux. The reason why is because the .clear() function in VxWorks deallocates memory, which was not expected due to how it works in linux. So now you have a bug that took several months to find because no one felt they needed to dig into the STL code for VxWorks. And all because the coder wanted to simplify his or her writing process at the expense of knowing exactly what the code would do in all situations.

  62. Programming is people! by Anonymous Coward · · Score: 0

    And as such...you are gonna get the "clever" no matter what practices you write down.

  63. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 4, Insightful

    That is bad code, or at least, hideously idiomatic.

    The variable names are apparently chosen for conciseness over legibility. The choice of 'ss' as both the loop variable and as an important field name appears deliberately confusing, especially when combined with its terseness. And the termination condition relies on the fact that a null pointer is treated as false in a boolean context - this is a non-obvious and largely arbitrary design choice in the language, and is arguably a type error.

    I've been in this game long enough to recognise a linked list traversal when I see one, but I still had to read it twice to be sure. If it had read "for (currentNode = list->firstNode; currentNode != NULL; currentNode = currentNode->nextNode)" I'd have saved valuable milliseconds. If it had gone all OO and used some iterator object in a while loop, instead of that horrible for construct, even better.

  64. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    Idiom, what the OP lacks is the common idiom in the language. Like the traversing a linked list as you have pointed out.

    However, the code can improved by better naming of variables. The sin of the original code is to have the loop name be the same as a field in the struct, e.g. I think the following is more readable.

    for (it=s->next; it; thisThing=it->next);

  65. The Author probably shouldn't be programming in C by m6ack · · Score: 1

    The first example that the author sites as an example of poor programming is "idiomatic" C for traversing a linked list. Also, if the author can't deal with pointers, he should not only avoid C, but also C++ and stick to Java or his beloved PHP and JavaScript. Siting that he found a standards document so flugly as GNU "helpful," doesn't help his argument.

    First, learn C as C. Don't be scared, it's just like this "whole nother language" that's different from JavaScript. It can be used quite safely. If it couldn't, your beloved operating system of choice, that is likely written in C, just wouldn't work at all.

    Second, draw your learning of the language not from standards documents, but by immersion in books like "The Practice of Programming." You will then find out that code like "for(ss = s->ss; ss; ss = ss->ss);" can be used without fear of misunderstanding because it is "idiomatic." People that know C will fully understand what it is doing. Writing a comment here is pointless and will degrade the readability of the code.

    Third, add one further standards document to the list:

    http://lxr.linux.no/#linux+v2.6.32/Documentation/CodingStyle

    And learn that Coding standards are only as effective as those that use them.

  66. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 2, Informative

    C is a compiled language, so using long variable names has no effect on the amount of memory used at run-time

    It does if you're embedding symbolic debugging information in that same binary - and running it on a system where the entire executable is loaded into memory at start, rather than paging in sections as needed.

  67. Not a fix by abulafia · · Score: 1
    "Use autocomplete to avoid carpal tunnel and use long names" is not a fix for vague or misleading variable names.

    In some cases, it makes the vagueness problem worse, because a programmer namedSomethingDescriptivelyButIncomepletely or namedSomethingElseSomethingThatItIsNoLongerUsedFor, or JustNamedItPoorly. True, these are programmer errors, but that doesn't mean they go away just with the magic of long variables. At least with variables like 'erating', you have a signal that you should pay attention. Which of the super long variables in this legacy codebase you're coming up to speed on are correctly descriptive and which aren't?

    And don't get me started on halfassedly refactored Hungarian notation...

    "Well, use long variables perfectly" isn't a viable response, because it will never happen all the time.

    As far using autocomplete, I've tried to make peace with it. It just doesn't really work for me. Breaking the mental flow to futz with tab expansion or popup menus of options, well, is a break from the mental flow, and causes me to fall into futz with the UI mode, which is is a transition. Not a huge one, but it is annoying and non-helpful. I can work in noisy environments, but I don't like it, and it effects productivity. IDE "helpfulness" like this falls into the noise category, at least for me.

    --
    I forget what 8 was for.
  68. Unit Tests. by FooAtWFU · · Score: 1

    We address this matter with a fairly rigorous team-wide coding style (which is easier to impart because we do pair programming, which is a great way to expose new developers to the team's practices and the product's quirks) and a massive battery of unit tests. These tests effectively serve as the basic low-level documentation of how something is supposed to work. There are a few comments here and there (to label the unit tests, or if there's a particularly tricky / confusing / subtle line or behavior). The tests say 'what', the code says 'how', and the comments say 'why'. Even the best comments don't prevent you from writing broken code. A good set of unit tests does.

    We also wax a bit functional in our programming. You do need a modicum of competence to understand and write something like

    return sort { ... } map { ... } grep { ... } $obj->get_records(hashof_by 'name', @candidates)

    but once you have that, it's a lot easier to understand (and harder to mess up) than a series of loops that try to do the same thing. Functional programming is a good thing when you can do it: the matter becomes less of what the code does and more about what the code is.

    --
    The World Wide Web is dying. Soon, we shall have only the Internet.
  69. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    It took me 20 seconds to understand the code and it's over 9 year since I've programmed in C/C++. The "problem" is not the clever code but the new "clever" programmers.

  70. Re:author seems somewhat confused and inexperience by hey · · Score: 5, Insightful

    You make some good points but

    for(ss = s->ss; ss; ss = ss->ss)

    could be better written

    for(p = s->next; p; p = p->next)

  71. Congratulations on not reading the F***ing article by tomhudson · · Score: 1

    The statements you have "quoted" appear nowhere in the parent, or even in this particular subthread. Congratualtions on showing how people who think erating is a fine variable name tend to introduce unreadability wherever they tread ;-)

    FTFA:

    This brings me to my next point about coding standards:
    Names (method, function, class, variable) are important and programmers should not overlook them.

    Most of the variables in CRAP are one or two letters long. Originally, this was due to the memory constraints involved when programmers first designed and built the system. Some of the code guilty of one and two letter names was written in the late nineties. The explanation told to me was that CRAP programmers took it as a badge of pride that their code was so hard to understand and it was a sort of initiation test to new team members to understand the code despite the poor variable names. (My current teammates and I are currently rectifying this issue, but CRAP is a big system and it still is not always clear what dc or v do.)

    If you have a variable that is a rating of employees at an organization, b>organizationEmployeeRating is not a ridiculous name, while erating is.

    If you have a method that calculates the risk of an investment, name it calculateRiskInvestment(), not risk().

    A name should inform what the code selection does without needing to have intimate knowledge of the program.

    As for the rest, the blockquote tags are messed up ... but I'm sure an einstein like you can figure that out yourself.

    Blame slashdot's crap UI and lack of editing capability. Other discussion boards allow for editing/correcting, why not this one?

  72. You aren't making sense by coryking · · Score: 1

    What do you mean "Approximately X"? The compiler and the computer do "Exactly X"... where X is what you tell it do to.

    Are you suggesting there are languages that take my code and then instead of doing exactly what I wrote, they only kinda do what I wrote?

    Really, I'm not sure what you mean. You seem to be operating and multiple levels. Are you talking programming languages, overall architecture, what?

    1. Re:You aren't making sense by joaommp · · Score: 1

      at any level, actually, this can happen. I'm talking, just for example, when for the sake of readability, a specific construct is replaced by other believed to be equivalent or, that usually is, but that in some specific situations that might (or not) happen in the final application of the project being develop, might lead to unexpected or different results. There are many different situations that can result in something like this. And we can't all expect every programmer to be the perfect genius and know every single possibility by heart to always know when, in the case I mentioned, he will have to do some additional work to make sure that the changes he made do not affect the outcome. People don't all know the same. Somewhere, sometime, there will be people that might be absolute genius, but, for some reason, didn't learn one specific key of information that was important to that particular case, to properly handle the replacement of that one specific construct for the other believed to be always equivalent but which, in fact, is only equivalent if some other strange or far-fetched condition is also met and that is mostly assumed to be true.

    2. Re:You aren't making sense by coryking · · Score: 1

      In otherwords, a "fix" in one place might break a dozen other dependencies you didn't know about?

      I'm still unclear what you mean.

    3. Re:You aren't making sense by joaommp · · Score: 1

      yes, for example.

  73. Re:Some of the complaints aren't valid by Toonol · · Score: 2, Insightful

    Other than about the pointers, I tend to agree with the author rather than you on the points you mention. Which is fine, I suppose; we don't all need to program the same way, and it's probably good that we don't.

    But my thinking is that longer, more descriptive variable names are simply part of documentation; it can eliminate the need to look through the code and find the comment tied to the declaration. (Although I personally dislike the 'initial lower case, capitalize all subsequent words' standard.) As far as skipping the brackets on single line blocks after conditionals... I think that is ALWAYS a bad idea. It's a pointless, inconsistent shortcut that can cause a number of different mistakes, just for the convenience of saving two characters. Yes, you can learn to always watch for that; but that's a learned response to a problem that doesn't need to exist. Better to avoid the problem in the first place. Adding the brackets never hurts anything, it increases the consistency of your formatting, and reduces potential mistakes... that's exactly the sort of thing that belongs in a standard.

  74. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    I got a more modern example as well. The 'number one financial terminal supplier' makes use of enormous executables, basically all the different screens linked together into a single program. Eventually the executable size (with debugging information) hit 2GB and would not run on a certain UNIX operating system... they had to reduce variable name length whilst waiting for an emergency kernel patch.

  75. Re:author seems somewhat confused and inexperience by FlyingGuy · · Score: 0

    Hmmm, sorry to disagree with you but if you were working in my shop and you wrote something like that, a warning of "That's enough of that shit" would be immediate. Repeating that behavior would result in an invitation to go practice your "craft" elsewhere.

    As many many others have pointed out in this and other articles on the same subject there is little to be gained by this type of nonsense and in many cases much to be lost. An as another poster pointed out in a reply to your post, the reliance on a null pointer being treated as boolean is both risky and stupid since form one compiler implementation to another that evaluation is subject to change. even if you wanted to write this statement this way then to make it at least a proper statement then it should be: "for(ss = s->ss; ss!=null; ss = ss->ss);" ss != null is guaranteed to evaluate as boolean ss simply being null is not.

    --
    Hey KID! Yeah you, get the fuck off my lawn!
  76. Try working at EA by Anonymous Coward · · Score: 0

    I worked for Electronic Arts in the '90's where nothing was documented. Not the code, not the tools, not the processes. During the final month before release, there would be a daily build and some teenagers would beta-test but there no other QA, no doc's, no reviews. Oh, they did have the "Wall of Shame" as I called it where bugs were assigned to specific coders. Great moral booster.

    One tool I was required to use, specified all its time units in 1/100th's of a second. Another expressed amplitudes in dB mapped onto 0...75. None of this was commented or documented anywhere. You just had to unit test everything you touched to grok it's behaviour.

    Needless to say, it drove me mad, espec. because I couldn't figure out why people were so resistant to change. All the programmers would just skunk away in the cubbies for weeks at a time, and keep the code to themselves like a shameful personal secret.

    In the end, I figured the secrecy and lack of doc's was due to the company's vicious turnover rate; people figured they were less likely to be fired if they were the sole knowers of something. Also, no-one really wanted to help anyone else -- it was a very dog-eat-dog environment, with office politics trumping everything else.

    From EA's point of view, I think it was actually cheaper in the end to have 20-something clueless coders churning out throwaway versions than to hire savvier, more experienced programmers. The buggy version would be replaced by next year's buggy version anyway. And by creating a paranoid work atmosphere they also managed to suck a lot of unpaid overtime out of people.

    My suspicion after 20 years of professional life is EA is not exceptional. Academics and programmers tend to agree on the need to document, test and verify, but in the business world the reality is that quick-n-dirty is cheaper. I've read all the arguments that debugging is more costly than coding, etc. but it's just not borne out by practice.

  77. b4 u were born, sonny... by airdrummer · · Score: 2, Insightful

    i worked on fortranIV code that had been migrated from fortranII that had been migrated from whatever language was used on an ibm drum-memory machine;-) there were variables named for drum memory locations, 4col...i wasn't about to change those;-)

    and those codes were written by the resident gas properties genius, who was still on the job;-) it was then i realized that the clarity of code is inversely proportional to the brilliance of the coder;-)

  78. FTFA: is called an external reference by Zero__Kelvin · · Score: 2, Insightful
    This time you got it right and added an external reference (FTFA), which is appropriate since the quote was outside of the scope. You see, when you write for readability you don't use variable names like erating and comments regarding code outside of the current scope include references to the source to which you are referring. I didn't really need you to make the point that people who think erating makes a great variable name don't know how to write for readability again, but thanks for really driving it home ;-)

    "Blame slashdot's crap UI and lack of editing capability. Other discussion boards allow for editing/correcting, why not this one?

    Yes, you are right. It is Slashdot's fault that you didn't preview before you posted, and it's the compilers fault when you don't #include the header file that resolves external references.

    "but I'm sure an Einstein like you can figure that out yourself. "

    You just run willy nilly with all the rules of writing, now don't you ;-)

    --
    Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    1. Re:FTFA: is called an external reference by tomhudson · · Score: 1
      If you don't see something in the thread, you read the summary. If you don't see it in the summary, you read the article - you don't go and throw a hissy fit because you're too lazy to read the article.

      And as for the blockqutoe tags, this is an EXCELLENT example where going minimalist is better - <q> rather than <blockquote>, since they don't allow inline quote tags - or they could just make their own <quote> tag, same as plenty of other sites do.

      It's about minimizing typos. It's a problem that has caused a few flame wars here and elsewhere, and can easily be fixed by going to shorter tags AND by fixing their broken system so that people can edit posts. It's not complicated - certainly not rocket science - and a lot of people have complained about it over the years.

      "an einstein" is not a person or a place, so no caps needed. Or do you also capitalize fermion (named after Enrico Fermi), or jesus-freak. Next you're going to want to capitalize the acronyms html, dna, and laser. Styles change - none of them need to be capitalized any more, and I can't remember the last time I saw anyone capitalize laser.

    2. Re:FTFA: is called an external reference by Zero__Kelvin · · Score: 1

      "... AND by fixing their broken system so that people can edit posts.

      They don't allow that because people who say stupid things will go back and edit them later to say that they didn't. They could keep histories like they do in Wikis, but that would add a lot of overhead because so many people say so many stupid things on Slashdot (and I'm guilty of that too), but I can certainly see why you would want that capability:

      '"an einstein" is not a person or a place, so no caps needed.'

      It is amazing how I did that without a blockquote tag! I can see why you called me an Einstein!

      --
      Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    3. Re:FTFA: is called an external reference by tomhudson · · Score: 1

      They don't allow that because people who say stupid things will go back and edit them later to say that they didn't. They could keep histories like they do in Wikis, but that would add a lot of overhead because so many people say so many stupid things on Slashdot (and I'm guilty of that too), but I can certainly see why you would want that capability:

      Other systems put <strike> tags around the original text you want to change - which is the original purpose of strike-through text, btw. Also, if even THAT is too much, there's no extra "overhead" in doing an "append-only" to the original post, so it makes it clear what was the original and what was added. I'm sure you've seen lots of sites that do that - even big news organizations, where they'll have update or correction appended to the original text. Put the update, along with the timestamp; eg
      update 2010:02:30 We've added a new day to the calendar- February 30th!.

      There is NO excuse for not adding at least an "append-to-original-text" mode for the quick fixes, or for adding additional citations, etc., rather than have the citations duplicated in multiple responses. Ditto for corrections. The only down side is it would cut down on page views and allow for fewer flame wars, so fewer ads shown.

  79. it doesn't actually traverse a linked list... by Anonymous Coward · · Score: 0

    ... in any _useful_ fashion. Notice that semicolon at the end of the line after the closing bracket?

    D'oh!

    1. Re:it doesn't actually traverse a linked list... by Anonymous Coward · · Score: 0

      for(ss = s->ss; ss; ss = ss->ss);

      This loop isn't useless, TFA just didn't cover how they overloaded the -> operator.

    2. Re:it doesn't actually traverse a linked list... by Anonymous Coward · · Score: 0

      This loop isn't useless, TFA just didn't cover how they overloaded the -> operator.

      Nice one Einstein. Since you clearly read TFA in great deatil, and so must be fully aware that this is plain old C, just like TFA clearly states, perhaps you'd care to enlighten us on exactly HOW you think they might have "overloaded the -> operator"? Idiot.

  80. Re:author seems somewhat confused and inexperience by phantomfive · · Score: 1

    When I first started using C, a lot of compilers only recognized the first 8 characters in an identifier name. Also, the CBM basic interpreter only recognized the first two characters (you could use more, but they would be ignored. I am sure I was not the only one who responded to this by only using 1 and 2 character length variables. Not saying it was a good idea, I'm just saying I did it). So a C program with only two character variable names doesn't seem unlikely to me.

    Agreed on your second point. Some coding tasks are complex, and require complex code. If he gets confused by linked list traversal and alternate bracing styles.........may he never look at networking code. It will kill him.

    --
    Qxe4
  81. Autocomplete by coryking · · Score: 1

    A good autocomplete implementation works just like tab completion in a good shell. Type as little of something as you need and hit tab.

    Both Visual Studio and Eclipse auto complete seems to almost work as good as a tab completion in bash. A lot of the text editors I use usually have shitty implementations that pop up so soon they really dont even know what I'm trying to type. Honestly, I cannot even explain why the auto-complete in VS just works, nor can I explain why autocomplete in my text editor sucks--my fingers and brain both get along with one and fight the other.

    I also wonder if those who abhor auto-complete are also people who are hunt & peck typists. If you are busy looking at the keyboard while you are typing, then any kind of auto-completion would be annoying. You might be typing away and not notice the focus has shifted from the code to some list.

    1. Re:Autocomplete by abulafia · · Score: 1
      Eclipse doesn't work for me, and I haven't used VS, so I can't comment. Still a gvim guy.

      On the command line, I generally type things out. I use tab expansion when sitting in directories full of evilly named files (although if that is bad enough, I resort to copy/paste, because the lost speed isn't worth the lost accuracy when starting at a thousand files named things like 200911061654230001.log).

      I touch type. My typing isn't "school typing", being self taught (I reach for the 'y', for instance), but when not writing Perl and writing things that don't require much thought I do between 75-90 words/minute. Three cheers for clicky keyboards!

      --
      I forget what 8 was for.
  82. Re:author seems somewhat confused and inexperience by hey · · Score: 1

    Is there any C/C++ compiler in existence where NULL is not a boolean false ?

  83. Art vs. Construction by OpinionatedDude · · Score: 1

    The proponents of the two sides of this "argument" seem to me to be artists and constructionists. In software, art is what happens at a hacker conference or at a startup BEFORE the investors start poking around. Construction (including architecture and source control and coding standards and design patterns et. al.) is what happens at a medium to large company that takes huge amounts of skilled workers to build something that can then be charged for in copious amounts and which will then make investors rich. In short, hacking vs. coding. Both have a place in the world. Neither should be influenced by the other. The big problem with software is that the former usually morphs into the later rather than being a completely separate effort which should include none of the original source material and none of the original players. And finally, a good hacker is NEVER a good coder, and a bad coder is often NOT a gifted hacker, but someone who shouldn't be doing either type of work.

    1. Re:Art vs. Construction by iplayfast · · Score: 1

      You've got no idea what you are talking about.

  84. he is a joke by Anonymous Coward · · Score: 0

    He makes some good points about naming symbols, but: the guy does not recognize a for loop scanning a linked list (and even think it is a "clever" trick) and does not know that he can automatically indent his code under vim.
    He is a total joke. He should look for an other job.

    1. Re:he is a joke by Anonymous Coward · · Score: 0

      I forgot to add: what the fuck is he meaning when he talks about old hardware putting ridiculous constraints on variable name length. This is just utterly stupid, and even more than that because he talks about C...

      Nothing is worse than a novice who thinks he has some valuable experience to share and only tells bullshits in a long blog posts. What is sad is that most programmers' blog posts are like that.

      And he even cite the old stupid meme that comments could be unnecessary is the code is self documenting. This is fucked. There is no such think like self-documenting code without comments. You ALWAYS have something to explain that either can _not_ be expressed in plain code, because in a real world system there are always algorithm that are inherently tricky, and even when there is not you still have to explain transverse design decision that sometimes can not even be inferred from the code because there still is not enough of it.

  85. Modernized Literate Progr with Outlining by unixtechie · · Score: 1

    My idea, in answer to your question, would be modernized Literate Programming combined with outlining.

    Traditional-style lit.prog. is done in flat files, and one has to keep the structure in one's memory.

    Combination of lit.prog with outlining or folding will relieve short-term memory, eliminate switching between "housekeeping" and navigating and programming, and will scale literate programs.

    Secondly, traditional lit prog erects an unsurmountable PSYCHOLOGICAL BLOCK before a programmer demanding that he produced a "polished essay" of a program.

    Lit Prog must be used as PROGRAMMING FROM SPECIFICATIONS IN HUMAN language, as programming in pseudocode which becomes precise new meta-operators, and be free from the demand of nice exposition.

    Rather, if practised as a tool to help keep notes, ideas, lists, references alongside your code snippets, it becomes an accelerator, rather than a drag on your feet.

    And thirdly, lit prog must be - on 90% of uses, which are by practicing programmers rather than paper-producing academics - rid of its dependence on TeX or LaTeX.
    The most ubiquitous markup today is HTML.

    I wrote a script which implements these ideas, and called it Molly for "MO-dule for LI-terate programming":
    http://github.com/unixtechie/Literate-Molly

  86. Re:author seems somewhat confused and inexperience by Kjella · · Score: 1

    He uses this code "for(ss = s->ss; ss; ss = ss->ss);" as an example of bad code: "For those of you that are interested, the line traverses a linked-list of sources and sub-sources to process the values inside. But it took a good deal of research to figure that out, because there were no comments and the variable names, well, suck." Well, I read that and said to myself, "It's traversing a linked list."

    If you see the pattern yes, but the naming is just horrible. "for(ss = s->first; ss; ss = ss->next)" would be quite easily understandable. Plus it'd match the typical first/last next/prev way of naming usually done in a doubly linked list. I would not immediately understand that, particularly not if it wasn't obvious from the function that it would be looping through anything.

    I think everyone should be forced to do what I did when I programmed on my TI-82 calculator, it had no autocompletion and variable names were painful to repeat so they became single letters. I could do quite advanced stuff as long as I kept working on it and had it fresh in memory. Tried looking at it later, it was a complete clusterfuck to dechipher.

    This guy looks lof the same caliber, s->ss and ss->ss as member variables? I mean in a function you can use almost any lame naming and people should be able to figure it out because the whole purpose of the variable is right there in the function, but if it's not clear what the members are you have to dig through the whole class and find when, why and how it's being set and/or used.

    I don't really mind pointers, but they have a way of adding a very confusing layer of indirection that often makes it unnecessarily complicated to understand what's doing on.

    --
    Live today, because you never know what tomorrow brings
  87. Re:author seems somewhat confused and inexperience by noidentity · · Score: 2, Insightful

    He uses this code "for(ss = s->ss; ss; ss = ss->ss);" as an example of bad code

    I love how his example uses the most confusing variable names possible. Just using proper names should make it clear to almost anyone:

    for ( Item* p = foo->items; p != NULL; p = p->next )

  88. It's just discipline by thethibs · · Score: 1

    You've answered your own question: an elegant one-liner coupled with a comment from a few revisions ago makes for a good headache.

    Clever code and maintainable code are not antagonistic. Clever code that's well commented is as maintainable as the more pedestrian type. There are two problems.

    The first is that the second version is often an awful hack by a programmer, not the one who wrote the original code, who doesn't fully understand what the code is doing. There is no law, not even a best practice, that says all code, even well-commented code, must be comprehensible to someone with a two-digit IQ.

    The second problem is getting said programmer to comment what he did. I suspect in many cases he doesn't know, except that the immediate symptoms have gone away. I call this a goat's blood and chicken feathers patch. Unintended consequences will be someone else's problem.

    Maintainability is only one of many important quality attributes. I've written more 'clever' bits of code than I care to count, usually because the alternative would result in failing some other measure--response time, size, reliability, you name it. In every one of those cases the comments provided a technical manual for the subject code.

    There's one case I won't forget where 14 lines of assembler was supported with 40 lines of comment, not including the comments on each line. I was invoking little-used and poorly documented features of the cpu chip and using them in an interesting way, and an explanation was appropriate. This code still runs fine on a modern PC. (If anyone is interested in a really fast x86 triple precision integer division that handles the signs of the quotient and remainder according to the Forth standard, I've got one.)

    Clever code isn't the problem; poor documentation by poor programmers is the problem.

    --
    I'm a Programmer. That's one level above Software Engineer and one level below Engineer.
  89. write insanely obvious code by Anonymous Coward · · Score: 0

    If you build obvious enough code, you only need a few comments, such as "this business thing that does so-and-so starts here/ends here". All the comments in the world don't make a "clever" solution any less douche-y.

  90. Re:author seems somewhat confused and inexperience by coryking · · Score: 1

    And this is relevant to 99.9% of the software out there how?

    "Facts" like this are what turn into programmer urban legends that haunt us forever. "Facts" like it is better to manually inline your code rather than let the compiler do it. "Facts" like if you are just copying a string you should do the pointer arithmetic yourself rather then "wasting space" pulling in the standard library for strncpy. "Facts" like with .NET you should always set variables to "null" to save memory. All rumors. All urban legends. All passed around like they are the truth.

    When you make statements like yours, make sure to add *huge* guard bars. You comment only applies to a very, very narrow range of programs in the wild. In fact, if you worked on such a system you'd know this applies to you automatically.

    In other words, your comment is garbage--write descriptive variable names and don't fucking worry about "saving memory" or "saving disk space" unless you are an complete idiot. If you are working on a system were long variables eat into your 10k of flash memory, then we can talk--though I'd question why you are embedding such detailed debug info in your device in the first place.

  91. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 1, Informative

    Is there any C/C++ compiler in existence where NULL is not a boolean false ?

    No. The language requires that Null is always zero. It also requires zero to always evaluate to false and anything non-zero to always evaluate to true.

  92. Re:author seems somewhat confused and inexperience by Tacvek · · Score: 1

    It takes me one second or less to recognize that "for(p = s->next; p; p = p->next)" is iterating a linked list, or a close relative thereof. It definitely takes several seconds for me to recognize "for(ss = s->ss; ss; ss = ss->ss)" as doing the same. At first glance it looks like the initial and loop conditions are the same, thanks to using "s" and "ss".

    I'm also not particularly used to seeing a for loop being used for linked list iteration. I'm familiar with for_each loops for the purpose, in languages that have such a feature, otherwise the code I see tends to use while loops for this. The for loop form is actually better in that experienced programmers can quickly recognize it by the structure of a single line, while the while loop requires scanning multiple lines.

    This is not nearly as bad as say Duff's Device which would be very confusing upon seeing it for the first time.

    --
    Stylish sheet to fix many problems in Slashdot's D3: https://gist.github.com/801524
  93. Where is the processing? by Zero__Kelvin · · Score: 1, Informative

    for(ss = s->ss; ss; ss = ss->ss);

    The semicolon at the end means the loop is only "processing" in the middle statement. Testing to see if ss is NULL does not processing make. Either he took liberties and left out the loop payload, or he still missed something and still doesn't understand it. It is true that in an embedded system, merely reading an address can have side effects, for example reading a register can cause hardware to perform actions, etc., and maybe that is what is what is going on here, but I doubt that is the case here since the addresses would have to be pointers to other registers and registers themselves at the same time (though it is still conceivable.)

    I believe he meant to write: for(ss = s->ss; ss; ss = ss->ss) { [some kind of processing here] };, but that is not what was written, which is ironic in an article complaining about unclear writing of any kind.

    I agree that the variable names aren't good for code written today, but C was written in the late 1960s when core (i.e. memory of the day) was expensive, and NASA has been around that long of course, so maybe at the time the code was written it was good code (and yes I know the size of the executable won't be bigger, but the size of the source will be, especially if s and ss are used throughout a large program, and source code lives in memory when being compiled too.)

    He certainly shouldn't have needed more than a few seconds to figure out that the loop traverses a linked list.

    --
    Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
  94. Did somebody mention FOSS? by Zero__Kelvin · · Score: 1

    "To my mind, the MAIN criteria for arriving at a maintainable codebase is OWNERSHIP, OPENNESS, and COLLABORATION."

    I agree with you. Open Source is a better paradigm ;-)

    --
    Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
  95. In my experience... by Lord+Bitman · · Score: 1

    If naming (variable, function, class, module, whatever) isn't part of your coding standard, you're going to have problems.
    And pretty much everything else is just an optional "nice to have" (usually to do with spacing).

    I am the asshole with the 40-character variable names. Yes, I need to split statements over multiple lines lines sometimes, yes I have more lines of code and it takes me longer to type them, but I think it's very worth it to be able to pick something up months or years later and instantly be able to tell what the hell everything means.

    As for spacing, I would absolutely love to format all code very strictly, and reject any commits which don't match an automated formatter exactly (for XML, this is possible, of course), but I've yet to see one which doesn't have really horrible edge-cases involving comments.

    --
    -- 'The' Lord and Master Bitman On High, Master Of All
    1. Re:In my experience... by arjan_t · · Score: 1

      I am the asshole with the 40-character variable names. Yes, I need to split statements over multiple lines sometimes, yes I have more lines of code and it takes me longer to type

      Luckily, most of today's IDEs offer you variable name completion. Just enter a few letters, hit something like ctrl+space and the IDE completes the name for you. Using long variable names doesn't necessarily means you have to type more.

    2. Re:In my experience... by InfiniteLoopCounter · · Score: 1

      A real problem with long variable names and strict formatting (spacing, line width, etc.) can come about when moderately difficult mathematical formulas have to be coded (and lots of them sometimes). I wouldn't want to read variable names longer than x,y,z, v (or maybe vel), etc. and function names longer than sin, cos, etc. in an actual formula. Nor would I want a single line of code split over 10 lines or for that line to be completely unaligned mathematically.

      Sorry if I am falling into the same trap as many others here, as well as the the author of the article, and generalizing too much.

    3. Re:In my experience... by Lord+Bitman · · Score: 1

      Breaking down one large step into several smaller steps not only gets around the problem of "a bunch of really long variable names in one place", but also improves readability.

      This can be the functional way (lots of small one-time-use functions), or the procedural way (lots of variables turn into fewer variables over a series of smaller steps)

      When programming, I can't think of anything more important than the ability of a human to understand what the code is trying to do. I would say this is more important than the code actually doing anything at all.

      --
      -- 'The' Lord and Master Bitman On High, Master Of All
  96. Always write code as if... by ebbe11 · · Score: 1

    ...the guy who is going to maintain it is a 6'6" bodybuilding psychotic maniac who knows where you live.

    --

    My opinion? See above.
  97. Code editors by arjan_t · · Score: 3, Interesting

    We deal with this by using something that can be described as code editors.

    These are people that edit raw code committed by other programmers and refactor it in order to comply with a set of standards. Editing may entail just changing a few variable names, but it can also be almost a complete rewrite of the code. Of course, if code rewrites become the rule rather than the exception, something is wrong and some serious talks with the original programmer will be necessary.

    As long as the code editors are knowledgeable people and agree among themselves about the specific style, best practices and architecture to be used, this can greatly improve the quality and consistency of the code.

  98. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    The original article referred to the program being developed on a very old system and the comment to which I replied inferred that the chosen short variable names had no benefit. I was pointing out why the code he's looking at now might be the way it is, not suggesting everybody writes code today with single letter variable names.
    Get back to your fucking visual basic programming and leave me to my $400,000 + ~40% bonus lead financial programmer role.

  99. Seatbelts are useless too! by Zero__Kelvin · · Score: 1

    "A college professor at Texas A&M, Dr. Salih Yurtas told us that he believed comments were useless. His argument was that people rarely pay enough attention to code comments and that since developers often add them at the last minute after the program is finished, they are often incomplete."

    Right, and seatbelts are useless because people often don't use them, or they fail to buckle them properly.

    --
    Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    1. Re:Seatbelts are useless too! by iplayfast · · Score: 1

      Actually I agree with the professor. Overtime code will change, and comments rarely are kept up with the same level as the code. I therefore don't read comments as often as just looking at the code. (Hence the saying "comments lie")

      I also rarely comment as the code is created with enough information that it has the commenting built in.

      The only time I comment is when something is happening that is not obvious from the code, or which explains the background thinking behind doing something a certain way. Basically just notes to myself to remind me (or the next guy) what thoughts went into it.

    2. Re:Seatbelts are useless too! by Zero__Kelvin · · Score: 1

      "Actually I agree with the professor. Overtime code will change ..."

      Well, see, there is your problem right there. You are using consultants and paying them overtime! Real salaried programmers don't tend to change perfectly good well documented code just to get overtime ;-)

      I'm starting to see your logic here though, and I really like it! I'm going to recommend everyone stop writing requirements documents, because after all, they will change! Also, no more need for a Wiki ... the friggin content will just change anyway! You just don't seem to get it that you are arguing that comments are not helpful because some programmers aren't good at their job, and that you are using the (il)logic to become one of those yourself.

      "I therefore don't read comments as often as just looking at the code. (Hence the saying "comments lie")"

      So in other words, if there is an error in the source file, you ignore it rather than correcting it. I'm starting to see why you agree with the "professor"

      "The only time I comment is when something is happening that is not obvious from the code, or which explains the background thinking behind doing something a certain way. Basically just notes to myself to remind me (or the next guy) what thoughts went into it."

      Well, that sounds perfectly sane, until you realize that the next guy isn't reading your comments anyway because you shared your "wisdom" with regard to comments with him in the code review last week. (WTF am I saying? Code review? Who the hell does those? They are useless!)

      --
      Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    3. Re:Seatbelts are useless too! by iplayfast · · Score: 1

      You are so busy being sarcastic you don't examine what I'm saying.

      Suppose you are dealing with code that is greater then 4 years old that has had several hands involved in it. You are asked to add some functionality to the program.
      You need to find out where in the code that functionality should go, and add it in an appropriate place.

      So are you going to understand what the program is doing by reading the comments or the code? If you've had any experience you will of course read the code. The code has been tested and works, while the comments are only what some programmer thought he was doing.

      What I'm saying is you should write your code so that comments are superfluous, and if the comments are superfluous then why are you writing them. The reason you would write them is when the code doesn't explain what you are trying to do.

      Or you could just rant and rave that the comments don't make sense and therefore you can't change the program.

    4. Re:Seatbelts are useless too! by Zero__Kelvin · · Score: 1

      "So are you going to understand what the program is doing by reading the comments or the code? If you've had any experience you will of course read the code. The code has been tested and works, while the comments are only what some programmer thought he was doing."

      A sign of a competant programmer is that they know when things are mutually exclusive, and when they are not. I'm going to understand it by reading the comments and the code. Suggesting that I do otherwise is an indication that you lack experience, competance, or both.

      "What I'm saying is you should write your code so that comments are superfluous ...

      Bullshit. If that were true then Linus Torvolds wouldn't be accepting code into the kernel that had comments in it. A superfluous comment is a useless comment. There are times when comments are not superfluous, and no amount of coding will communicate what the comment does. For example "I know it would be smarter to do X, but we need to do it this way to be compatible with third party Y's clusterfsck code" is but one example of such a comment. I wrote that "Good source code is compileable documentation" more than ten years ago. You can see someone quoting me as proof here. I never the less knew then, and re-iterate now, that comments are useful, and necessary actually, if you ever want to learn how to be a truly good programmer. In other words, in order for source code to be compileable documentation the person writing the code needs to know how to comment properly. Period.

      --
      Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
  100. Canonical examples of chutzpah? by turing_m · · Score: 1

    I would think that correcting Knuth on programming practice has got to be way up there.

    You might also consider telling the computer to use some line breaks when you separate your paragraphs, since the aim of slashdot is ostensibly to communicate with other people.

    <br><br>

    does the trick.

    --
    If I have seen further it is by stealing the Intellectual Property of giants.
    1. Re:Canonical examples of chutzpah? by joaommp · · Score: 1

      I'm not trying to correct Knuth. I was just analyzing that isolated sentence, like I've already explained in some other comment...

    2. Re:Canonical examples of chutzpah? by maxume · · Score: 1

      Slashcode actually does a pretty good job of inferring intent when using plaintext mode (so two line-end characters in a row get interpreted as a paragraph), but if you really want to use html, why not use it correctly and just put in a <p>?

      Or am I missing sum bizarre subtlety in your post?

      (there is even some sort of tidy functionality that closes tags and things...)

      --
      Nerd rage is the funniest rage.
    3. Re:Canonical examples of chutzpah? by jeremyp · · Score: 1

      Do you think it's fair to analyse a single sentence in isolation? Here's a sentence in isolation:

      To suppose that the eye, with all its inimitable contrivances for adjusting the focus to different distances, for admitting different amounts of light, and for the correction of spherical and chromatic aberration, could have been formed by natural selection, seems, I freely confess, absurd in the highest possible degree.

      Charles Darwin wrote that at the beginning of chapter 6 of The Origin of Species and it's much beloved of creationists because it seems to be evidence against evolution. Of course it's really just a set up for the next three pages explaining how the eye evolved.

      Anyway, the point is that you should be analysing ideas expressed, not just single sentences.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    4. Re:Canonical examples of chutzpah? by turing_m · · Score: 1

      Slashcode actually does a pretty good job of inferring intent when using plaintext mode (so two line-end characters in a row get interpreted as a paragraph), but if you really want to use html, why not use it correctly and just put in a <p>?

      I used to do that, then it stopped working for some reason. So I tried the next one along in "Allowed HTML" figuring it would be a "break" with the aid of preview until I got the desired outcome. It appears to be working again, I'll go back to using <p>. ;)

      Maybe the original reason it stopped working is because I screwed up somehow, maybe not. The comments come out the same way, slashdot doesn't break, and hopefully no one is reading my comment in the original. I make no claims about knowing any more html than is necessary to output a roughly readable slashdot comment.

      No bizarre subtlety was intended by my use of the <br> tags. Hopefully the other subtlety was not lost; that if you make the case that the end user is king, then in the case where you are programming to please the end user (e.g. writing html) you should strive for readability and elegance.

      --
      If I have seen further it is by stealing the Intellectual Property of giants.
  101. Is this a clever one liner? by iplayfast · · Score: 1

    I like to use ternary conditions in my code where strings output based on a condional
    for example

    int n; //number of shoes
    printf("we have %d pair%s of shoe%s",n,n ? : "s" : "",? "es" : "");

    If you aren't used to it it is confusing, but if you are it saves a ton of code.

    Is it considered a clever one liner?

    How about
    while(1)
    { // do loop until return or break
    }

    My code is usually very terse, which helps me maintain it because dense code requires less reading to understand. (IMHO)

    1. Re:Is this a clever one liner? by iplayfast · · Score: 1

      And of course I mistyped the code.

      int n; //number of shoes // assign n
      printf("we have %d pair%s of shoe%s",n, (n!=1) ? : "s" : "", (n!=1) ? "es" : "");

    2. Re:Is this a clever one liner? by Timothy+Brownawell · · Score: 1

      And of course I mistyped the code.

      int n; //number of shoes // assign n printf("we have %d pair%s of shoe%s",n, (n!=1) ? : "s" : "", (n!=1) ? "es" : "");

      "we have 1 pair of shoe"
      "we have 2 pairs of shoees"

    3. Re:Is this a clever one liner? by iplayfast · · Score: 1

      Yup. Messed that one up totally. :)

  102. Be careful what you wish for... by gillbates · · Score: 1

    You just might get it.

    I have seen the opposite problem crop up: an institution so focused on creating code according to standards that they actually make the situation worse:

    • First, management belongs to a project management book-of-the-month club. Every project has rigid documentation and coding standards, but unfortunately, they are all different. Even if there were no comments in the code, it could be dated by the design pattern and/or coding style used. The result? A myriad of different, inconsistent coding styles, all the product of management directives.
    • The coding standards are laughable and outdated: I've seen requirements to use Hungarian notation, requiring macros for structure access (because, apparently, my_struct.my_field is just too confusing...), ridiculous namespace standards (why use a namespace if you're going to prefix the name anyway?), etc...
    • Mandatory comment blocks of monstrous size that make it impossible to see the forest through the trees. Yes, I understand documenting what is being done, or why, but there is no reason why a comment block should contain pseudocode describing the logic used. The code is already there!
    • Asinine physical design requirements, such as limiting files to only one function, making it rather difficult to view a group of functions as a logical module.
    • The required use of design anti-patterns, such as the Facade pattern, or the Endless-Wrapper pattern, where every OS call must be slowed down by an additional layer of indirection. Or, more frequently, the Class-Explosion anti-pattern, where even a strncmp() must be abstracted into its own class object.
    • The required use of symbolic constants instead of "Magic Numbers". The use of symbolic constants is normally a Good Thing(TM), except in cases where they make the code harder to read. Consider the following code: "ready = register & LOW_BITS;" So, which bits are set after the assignment? Oh, that's right, you can't tell without tracking down the header file with LOW_BITS in it. Granted, you can do this. But if you work with embedded software, it gets rather tedious after a few dozen times. "ready = register & 0x03;" is much clearer. Symbolic constants make debugging a real chore, because you can't verify the correctness of a statement merely by reading that statement; you must track down all of the headers. Worse, I've seen them nested more than 3 levels deep, split across multiple header files.

    So, be careful what you ask for, you might just get it. Generally speaking, it's easier to convince a sloppy programmer to write better code than it is to justify a deviation from already-established, albeit improper, coding standards.

    --
    The society for a thought-free internet welcomes you.
    1. Re:Be careful what you wish for... by arjan_t · · Score: 1

      The required use of design anti-patterns, such as the Facade pattern, or the Endless-Wrapper pattern, where every OS call must be slowed down by an additional layer of indirection

      • The Facade pattern is not necessarily an anti-pattern. It can greatly simplify access to a complex sub-system, but as with all things this pattern should be used moderately and with care.
      • Wrappers can be overused indeed, but "every OS call must be slowed down" is exaggerating. For starters, it's just a call, you don't need to qualify it with "OS". Secondly, modern compilers and runtime optimizers (e.g. the JVM), can inline calls. Inlining calls effectively nullifies any overhead. Furthermore, this overhead is very minimal on modern systems and finally, it only really matters when doing many calls in a tight loop. The average business request which runs in say 100ms is completely unaffected by the 'overhead' of 10 extra calls.
      • Putting things in lists is cool :P
  103. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 1, Insightful

    So you don't put up with "shit" like using widespread idioms and relying on standard language features? Sounds like a lovely place to work.

  104. Please pay attention to what Knuth said by Capt.Albatross · · Score: 2, Insightful

    Knuth is not suggesting one should be incorrect for the sake of maintainability, understandability, or anything else. In programming, if a solution is possible, there are infinitely many solutions, a few of them are easier to understand than most of them, and understanding is the key to verification and so to the writing of correct code.

    1. Re:Please pay attention to what Knuth said by joaommp · · Score: 1

      That is precisely my point... however, not everyone might interpret Knuth's sentence the same way. And no one has a hold on the whole knowledge available in the universe.
      Like I explained in some other comment, there will come a time when someone will be tempted to use, instead of the construct that person already knows it works, another one that, under a false assumption believes it works just as well, that may even look equivalent at first look, and all this for the sake of readability. Maybe something that most of the time would produce the exact same results, but that would depend on the state of some far-fetched condition. And somewhere, somehow, in some client, that condition would not be verified and all hell would break loose. Or it might trigger some cascading failure due to some dependency. There are probably countless examples of something like this happening.

  105. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    NULL is always 0 or (void*)0.
    The second method is commonly used on machines that have pointers of different lengths (For example, some crays have char* and int* of different lengths - they address completely different memory segments indeed)

    When you use 0 in a pointer context, the compiler replaces the 0 with a special bit-pattern, the "null pointer representation".
    On most modern machines this is also 0, but not necessarily. The bit-pattern can also be different for different pointer types (again on a cray,
    a char* null pointer representation is different from an int* null pointer representation)

    char* a = 0;
    On most modern machines, this will set 'a' to 0, but it could set it to '0xffffffff' on a cray.

    if (a) {
    The compiler will convert to something like
    IF A != NULL_POINTER_REPRESENTATION

    So, on a modern machine...
    IF A != 0

    On a cray...
    IF A != 0xffffffff

    That's why code such as
    char* a = 0
    if ((int)a) {
    }

    is not strictly portable. On a cray, the comparison would result in "false"

    That's why if you call a UNIX function such as execl(), which take a variable number of arguments, which
    are terminated by a char* NULL pointer you have to do
        execl("/bin/ls", "/etc", (char*)0)
    and NOT
        execl("/bin/ls", /"etc", 0);

    because otherwise the compiler will not know to replace the last argument with the null ptr representation, which may not be 0.

  106. So why do we use HLLs? by Capt.Albatross · · Score: 1

    A computer uses machine code, so why should we use higher-level languages? The reason is so they can be better understood by humans -- firstly and most importantly, by the author herself. Correct code can be written more quickly, and errors more readily detected, when using languages that approximate to natural (human) language, and Knuth is simply proposing that we go further in that direction.

  107. Unit tests best document software requirements by zQuo · · Score: 1

    A suite of unit tests document exactly the software specs for each software unit. It really improves modularity.

    Unit tests usually test for ambiguities and edge cases, and report back when results are not as expected. I've found that when programmers write unit tests, their code has far fewer stupid errors, just because they have to think about edge cases and boundary cases in designing the unit test. When finding unit interaction bugs, the unit tests make finding errors much easier... you already know the behaviour of a routine, and if there is ambiguous or incorrect behavior, it is time to extend the unit test.

    The extra time in writing unit tests is well worth it if the end software needs to be reliable or is going to be maintained over time. Total no-brainer from the organizational viewpoint. From the individual software developer's viewpoint, it's not so clear if the unit tests are worth it, especially if you probably won't be the one maintaining it. It's usually easier to write it without any tests, probably save about 30-50% of the time coding, use some of the time savings to fix any glaring bugs that crop up, and leave/blame the inevitable unobvious bugs to your successors. Or charge the client/company more to fix them.

  108. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    it's interesting that like many things, those least qualified
    to evaluate code, have the strongest opinions.

  109. Re:write obviously insane code by HornWumpus · · Score: 1

    Include ASCII graphics and cursor control characters in the comments so the code is unreadable.

    Use comments to record what the voices in your head and/or pants are saying.

    Make jungle noises at staff meetings before answering your shoe then running out.

    They will make you CTO.

    --
    John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  110. Not that hard. by paxcoder · · Score: 1

    The code mentioned on the linked page:
    for(ss = s->ss; ss; ss = ss->ss)
    I'm sorry, but that's obviously moving through a linked list untill the end (NULL == false) pointer.

    1. Re:Not that hard. by slcdb · · Score: 1

      Yeah, I stopped reading the article at that point. I immediately recognized that it was walking a linked list. I was expecting that his explanation would be something along the lines of, "Although this code *seems* to be walking a linked list, it actually does something *completely* unexpected... ". Nope... apparently it took him "a good deal of research" to figure that out. Which left me thinking, "Program much?"

      --
      Despite what EULAs say, most software is sold, not licensed.
  111. Yoda would agree. by Anonymous Coward · · Score: 0

    Words lead to sentences
    sentences to paragraphs
    paragrpaphs to books.
    books make you suffer.
    Suffering bad.

  112. This is why we use Python by Sarusa · · Score: 2, Insightful

    Well - one of the reasons we use Python. I'm sure some people will consider this a troll, but it's true. Some languages encourage readability, some don't. You can write horrible, awful, unreadable Python and you can write elegant, readable, maintainable Perl (Calcium was the best I've seen in a real product), but neither is encouraged and you know what you tend to get out of your programmers.

    This means our code takes a bit longer to write up front than just banging it out in Ruby, but has the advantage that when we come back to it six months later it's still obvious what's going on (even if someone else wrote it) and it's easy to maintain.

    Ruby's great (and a close match for Python in niche and functionality, which is why I'm using it specifically), but our Ruby guys can't do that because they love to make things as concise as possible - it allows them to show how clever they are. Perl-style magic variables and punctuation everywhere. They sometimes rewrite functionality from scratch because it's easier than deciphering their (own!) old stuff, which at least unit tests help with. On the other side, Python's indentation generally limits how much you can cram into one line without gross misuse of lambdas, which frees you from the need to even try it.

    Perhaps this is self selection - maybe boring people like me who learned to value maintenance considerations (thanks to hard experience) gravitate towards easy maintenance languages, which exacerbates the effect. But I think still think your choice of language will strongly inform how maintainable your code will be; you can mandate code policies for any language, but how often (and for how long) are those actually enforced in practice?

  113. I've not seen any corporate attention to quality by RonMcMahon · · Score: 1

    90% of my work has been in the Canadian Oil and Gas industry and EVERY company that I've worked for has sought 'get it done' above 'do it right'. In two decades of programming both as a consultant and as an employee I've NEVER had a code review. Even during my two years of Y2K work, whatever I delivered was just fine as long as the end client was happy.

    I've inherited systems where the documentation was literally four pieces of 3"x3" sticky notes that covered 'all I needed to know' about 28 in-production apps that I was now the sole supporter of. What was on those sticky notes? The user accounts and passwords for the Oracle database back-ends for the systems and the application names. As you can expect, in-code documentation was non-existent. When I attempted to improve the level of documentation for these systems (even just putting down the 'basics' of the system information on a single sheet of paper), I was threatened with dismissal for being too slow in working with these systems. The other developers who had to interface with these systems I now supported greatly appreciated this additional information as it empowered them and made their work faster, but only a few of them adopted the use of this single-page documentation solution for fear of pissing off the same management that had overseen the creation of this fiasco.

    Perhaps I've just been unlucky in my career and I've only stumbled into positions where results always override process, but since I've seen it in small companies, large multinationals and in three levels of Canadian Government, so I suspect that any talk about documenting systems and truly following 'best practices' is just so much BS. What management wants is results ASAP. When things fail it isn't management's fault, yet it is management that prevents systems from being built with adequate documentation and review because that takes longer and costs more, for which they are penalized, and when systems fail, it is the programmer who is at fault, not the manager.

    I figured that once I moved into management that I could become part of the solution, but then I found my VP giving me the same results pressure AND the developers who reported to me, ironically, simply wanted the code to be the documentation (The Agile 'the tests ARE the documentation' BS).

    Nowadays I simply program for myself and for my direct clients, and this is the only way that I've found to be able to ensure that systems are adequately documented without encountering a fight or threats on my employment.

  114. None of the complaints are valid. by mevets · · Score: 2, Insightful

    It is shorthand, and shorthand is contextual.

    If suddenly in the middle of a module to calculate the trajectory to return to earth, there is a reference to an out of scope notion like the employees rating; then a more descriptive name is very appropriate.

    If it is in a context which is doing computations about employee, department and company ratings, I would hope the person would be smart enough to use shorthand; otherwise all that annoyingly redundant crap just makes it more difficult to read and maintain.

    Why use sin() when it could be "RatioOfLengthOfFarSideOfRightTriangleToHypotenuse()"?

    How about "YCoordinateOfPointOnUnitCircleAtAngleFromOrigin()"?

    1. Re:None of the complaints are valid. by LordArgon · · Score: 1

      Why use sin() when it could be "RatioOfLengthOfFarSideOfRightTriangleToHypotenuse()"?

      How about "YCoordinateOfPointOnUnitCircleAtAngleFromOrigin()"?

      BadAnalogyGuy, is that you? :)

      Sin is is a well-known trig function. People are more-likely to recognize sin() than the other names you mentioned.

      At the end of the day, it's not about how short / long the identifiers are; it's about clarity. Brevity is nice, but it takes a backseat to clarity.

      Shorthand is only really appropriate if you aren't making it up on the spot. Unless your whole group agreed that e always stands for employee, erating is a terrible variable name, no matter your other context.

      And, honestly, I wouldn't want to work with a group that was so preoccupied with removing characters from variable names that they standardized on something like that. What's the point of inventing your own, cryptic, vocabulary? It drastically reduces code clarity and increases barriers to entry.

    2. Re:None of the complaints are valid. by spongman · · Score: 1

      ImaginaryPartOfTheNaturalExponentialOfTheAngleTimesTheSquareRootOfMinusOne(angle), surely.

  115. Code maintenance is an intractable problem by mstrebe · · Score: 1

    Exceptional programmers write code. They can't--can not--be paid to maintain the code of other people. They leave. They find other opportunities where their prowess and ability to think in code is appreciated.

    Mediocre programmers take any job they can get. They pore over the cryptic codex's of their thoughtful predecessors like acolytes transcribing the utterances of prophets. Their most important talent is that they stay.

    Code maintenance, therefore, is a non-starter. Architects and Engineers build buildings, and plumbers maintain them. Plumbers can fix a leak, but it'll take a while and everything will have gotten wet. They certainly can't re-engineer a chilled water delivery system to meet new building code requirements or calculate the pipe required to handle superheated steam.

    Extending the purpose or function of an application isn't "maintenance". It's re-design. It takes engineers, not plumbers.

    There's no amount of dumbing down that stupid can't be baffled by, but harnessing your Arabians to oxcarts will guarantee that your software never ships in the first place.

    I find it surprising that this isn't obvious to anyone who knows a decent programmer.

    --
    aka Matthew at SlashNOT/!
  116. Re:author seems somewhat confused and inexperience by dkf · · Score: 1

    And this is relevant to 99.9% of the software out there how?

    It isn't. Now. But if the code is inherited from the "olden days", then those stupid restrictions did matter back then. (I remember Ultrix. How I hated how Ultrix carried out linking. The old Linux a.out system was much nicer, despite being awful.)

    --
    "Little does he know, but there is no 'I' in 'Idiot'!"
  117. Pick the right algorithm, do the rest later by Lonewolf666 · · Score: 1

    There are huge differences between different algorithms, and picking the right one will usually sufficient without further optimization. For a very rough overview look at http://en.wikipedia.org/wiki/Big_O_notation.

    So choose an algorithm with favorable "Big O", implement it cleanly and try if that is fast enough. Only if that is not sufficient, try clever tricks.

    --
    C - the footgun of programming languages
    1. Re:Pick the right algorithm, do the rest later by MadKeithV · · Score: 1

      99% of programmers couldn't "big O" their way out of a wet paper bag.
      And also, in many cases of optimization, you may find that the "constant factor" of certain algorithms and hardware oddities (cache, SIMD instructions) actually overrides the theoretical performance benefits for most of the expected input data.

    2. Re:Pick the right algorithm, do the rest later by Lonewolf666 · · Score: 1

      99% seems a bit pessimistic, but I agree that understanding that stuff might put you among the more knowledgeable developers in many organizations.

      Considering constant factors versus "big O":
      In my experience most tasks with a count of input data low enough that "big O" does NOT dominate the execution time are fast enough anyway. Modern CPUs are your friend here and allow you to slack off a bit.
      Exceptions may include scripting languages and realtime applications.

      --
      C - the footgun of programming languages
  118. Re:Some of the complaints aren't valid by bzipitidoo · · Score: 1

    The article could have had better examples. That loop for walking a linked list was not hard to understand. Leaving out all the context was the only thing that made it even slightly obscure. Likely the author was spoiled by XML. 30 years ago, this guy would have been a COBOL programmer.

    The sort of bad programming I've seen is orders of magnitude worse than anything the author was complaining about. How about code that relies on compiler bugs to compile correctly? Code that is correct, but doesn't work because someone got clever and elsewhere in the program decided to call on system libraries to change how the OS responds to some events, to "fix" something totally unrelated? Naturally, when you undo damage of that sort it will break something somewhere else. Another fun one was the initialization code that didn't work and no one realized it because that code path was almost never taken. All it was supposed to do was create a few directories and files, for temporary data, however the installation software also did that, thus masking the problem. Then a clean up wiped them out, and suddenly the main program was crashing. Actually, since the main program did successfully create the first missing directory before crashing, the solution was to keep invoking it until it made it through the initialization. About 7 invocations as I recall, to get all the directories and files recreated. No need to fix that, right, since it will eventually work!

    --
    Intellectual Property is a monopolistic, selfish, and defective concept. It is "tyranny over the mind of man"
  119. Re:author seems somewhat confused and inexperience by syousef · · Score: 1

    Better yet.

    for(p = s->next; p != 0; p = p->next)

    Sure it's more verbose, but it's also more readable especially to a novice, since it's closer to the usual prototype of a for loop. (i =0; i xxx; i++)

    --
    These posts express my own personal views, not those of my employer
  120. The "Next Poor Slob" is quite possibly... you. by weston · · Score: 1

    My customer is the next poor slob who has to work on the source code

    Likely you. :)

    In most work situations, chances are better than not that once you create or touch something, responsibility for its maintenance is going to stick to you as long as it can.

    And right now I'm looking at some hobby code I wrote a year and a half ago. I was probably less careful than I should have been when I wrote it, because I knew the only reader/user in the near future was likely to be me. But "me" over a year later is quite possibly just about as clueless about what undocumented single-letter variables are and how a dozen functions fit together as a completely new initiate might be.

    1. Re:The "Next Poor Slob" is quite possibly... you. by Anonymous Coward · · Score: 0

      My customer is the next poor slob who has to work on the source code

      Likely you. :)

      In most work situations, chances are better than not that once you create or touch something, responsibility for its maintenance is going to stick to you as long as it can.

      And right now I'm looking at some hobby code I wrote a year and a half ago. I was probably less careful than I should have been when I wrote it, because I knew the only reader/user in the near future was likely to be me. But "me" over a year later is quite possibly just about as clueless about what undocumented single-letter variables are and how a dozen functions fit together as a completely new initiate might be.

      Ain't that the truth...

      I wish I had a nickel for every time in my younger days where I was working in some code, ranting to myself, "Who's the moron who wrote this crap?!?!"

      Then I look up the change log and I was that moron.

      Bad code will bite you.

  121. Mod parent up! by Traf-O-Data-Hater · · Score: 1

    Well he's at +5 already, but he has it spot on.
    When I talk to other programmers who can't see the value (or are lazy) in providing comments, I try to make it clear to them the comments are the RATIONALE for the piece of code. We know we can see a loop that iterates over a list, but why did Fred (who left before I started) write this module in the first place? He could have mentioned in a short blurb at the top that it updates a person's Mojo and that it's only used by the AustinPowers module, thus saving me time doing a global search on the thing. And given that I don't have any RATIONALE for Mojo.dll existing I sure as beans won't have any reference in AustinPowers saying the Mojo was moved into the YeahBaby common library because of some reason or other.
    RATIONALE. The WHY of the code, as so neatly put by the op.

  122. Clever Bad? Bollocks by Anonymous Coward · · Score: 0

    Any idiot saying clever doesn't pay the bills or clever is too difficult to maintain is simply admitting he's stupid. Grow some brains or get the fuck out of the industry. We do not want you, we never wanted you, and you are an infection.

  123. Ruby's literate by Steeltoe · · Score: 1

    This actually sounds like Ruby, which once you get past the powerful, yet seductive syntax, you can actually write things in a much more compact way, while retaining the readability. It doesn't go too far, like making the whole code like reading prose (too much text is also horrible), but mixes minimal syntactic sugar with text and good function/variable names, so that you can write iterators and whatever language extension you need, while retaining the original meaning of what you're overloading, or just use the common ones. Beats the hell out of for i = 1 to 100, although you can use that convention too as a stepping stone until you get the dynamic beauty of intepreted prototype-like languages like Ruby.

    Most Ruby libraries are actually thus very easy to read, since the same syntactic sugar are used over and over, to save lines of code, and convey the similar or exactly the same meaning, without repeating itself unnessesarily. It's neat to have one way of iterating, instead of so many variations like:
    for i=1 to 100 do
    i=1;while i = 100) break;end
    etc.. You can still do this in Ruby, but since all Ruby-libraries (which span everything you will ever need) follow ruby conventions like "duck" typing, you will eventually start using the more "rubyesqe" conventions more and more. They just make more sense and give more flexibility.

    Literate programming sounds neat, but actually Ruby with its DRY and other principles has practical solutions for spagghetti code. It does require programmers not indoctrinated with Perl though, as they will just go into their old routine to make a mess (just kiddin, almost ;-)

  124. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 1, Insightful

    What happens, then, when a single structure needs to be contained in multiple lists?

    You might try to dismiss that as not a good idea, but I'm thinking in particular about some structures in the Linux kernel where this is the case...

  125. Re:author seems somewhat confused and inexperience by Qu4Z · · Score: 1

    I disagree about NULL being false as being a largely arbitrary design choice. To me it reads as

    if (/* there is a */ thing)
        doSomethingWith(thing);

    To me, that's a hell of a lot clearer than

    if (thing != NULL)

  126. Mod parent up! by Steeltoe · · Score: 1

    My thoughts exactly when seeing that code. It just didn't compile in my head, so have no other comment about the other stuff grandparent post tried to convey ;-)

    Too much C / C++ in childhood.. Now it's Ruby all the way... ;-)

  127. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    Which suggests that you're not a C programmer. Fair enough, but you were warned:
    "The first sign of danger was the entire code base is written in C,"

    What this section of the article really lacks is a description of the struct(ure)s that s and ss point to. Maybe this is a simple linked list, and 'next' would make sense. Maybe it's a tree of some sort. Maybe ss had a contextual meaning that the author obliterated in his attempt to make a point.

    A cynic might point out that this is a self-confessed 'web development' author, but that would just degrade this post to his level.

  128. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    As a sophomore CS student, that code took me 10 seconds to figure out as a linked list traversal.

    I'm with the comment above: TFA author seems ignorant of pointers.

  129. Limitations of Emacs asm-mode by tepples · · Score: 1

    Use a modern editor that can store the strings of all previously used variables

    Allow me to rephrase: How do I tell the editor how to find "the strings of all previously used variables" in code written in the assembly language for a given microcontroller, specifically one with a 6502-compatible CPU core? Two ACs recommended that I look into Emacs with an appropriate major mode, but it appears asm-mode supports only indentation, not autocompletion.

    1. Re:Limitations of Emacs asm-mode by corbettw · · Score: 1

      Presumably you'd have to learn the configuration language for the editor in question and create your own macros to handle this edge case. It's unfortunate and could mean more work, it's up to you to decide if that extra work is worth the effort. But the option does exist, regardless.

      --
      God invented whiskey so the Irish would not rule the world.
  130. Re:Some of the complaints aren't valid by tomhudson · · Score: 2, Insightful

    You assume wrong. I've had to correct code because people coming from the Windows world NEVER turn on warnings. Many don't even know how to edit a make file. If there's no clicky thingee, they're lost.

    Anyone who cannot use make should not be writing c code. This is basic stuff. Then again, so is using ctags and fgrep.

    Ditto anyone coming from java. It's NOT the same, the mindset isn't the same, the conventions aren't the same, and someone with 10 years of java experience is totally useless when it comes to designing in c or c++. They try to make everything look like java, and they break things. And they keep on whining about needing garbage collection or smart pointers or the whole stl because they can't even write a simple linked list.

    If you can't write and manage a simple link list, a stack, a queue, and proper memory allocation in both c99 and c++, you should go back to java and leave c programming to c programmers. The guy who wrote the original article is a java programmer - look at the complaints and the references he provides.

  131. Re:Some of the complaints aren't valid by tomhudson · · Score: 1

    I look at the language standard. Look at the if() statement. It is followed by one line, and a semicolon. No parenthesis. Parenthesis allow you to group multiple lines (blockify) - and its' always possible to replace any block of code with a one-liner (either a function call, a macro, or even using the comma operator).

    Indent your code properly and you'll never have a problem with parenthesis - and your code will be more concise, thus easier to read.

    Adding brackets increases the visual pollution, and I really hate it when people put the opening brace on its own line - its a waste of a line. Folding editors can handle braces at the end of the line just fine - why can't people? Concise can be clear as well.

  132. Re:Some of the complaints aren't valid by tomhudson · · Score: 1

    Java is always interpreted - sure, at runtime, it does "just-in-time" compiling and caching of byte-code - but it has to INTERPRET that first. You can't keep the cache between program runs, for security reasons.

    The only exception is native code - which isn't java.

    The relevance to the article is that the article complains about how the code is wrong, but it looks fine to me, and I've been using c for decades. If you look at his "reference" section, you'll see he cites java style. Also, the idea that the stl is a solution is ludicrous in a c program. Ain't no such animal. And his example of a method name is also wrong, because (1) c doesn't have class methods, just functions (you can embed a pointer to a function in a struct, but it's not a "method"), and (2) you should be able, in a c++ program, to use the shorter method name because you get the context from the class name. That's the idea behind polymorthism - Man.paint() probably isn't the same as House.paint(). PolicyHolder.risk() isn't the same as CrossStreetBlindfolded.risk() isn't the same as RussianRoulette.risk(). You don't need to write PolicyHolder.riskOfPolicyHolderPayout(), CrossStreetBlindfolded.riskOfGetingHitByCarWhileCrossingStreetBlindfolded(), or RussianRoulette.riskPlayingRussianRoulette().

    Java programmers should not criticize c programmers unless they're ready to get some serious pushback, that's all I'm saying. There are a lot of things that are done a certain way in c for a reason. Conventions have developed over the last few decades, and c system code doesn't look at all like c++ application code. You can safely assume a certain level of expertise in system code - if the person doesn't have it, it'll be apparent quickly because nothing they do will work.

    It's like the engineering professor who proposed that the best test of their teaching ability would be to have the teachers take a ride in airplanes that their students designed. "That's no fair!!!" So finally, one of them asked "Would YOU get in a plane designed by one of your students?" "Of course. It would be the safest flight in the world - it would never get off the ground."

    It's not cryptic to confound others - that's just a side effect, but it does raise the bar, which is a good thing.

  133. Re:author seems somewhat confused and inexperience by FlyingGuy · · Score: 1

    Yes in fact shops I have run were lovely places to work. We wrote code that was both efficient AND readable, One day you might run a shop and when you have programmers of various skill levels having to follow some who wrote code like that you will appreciate what this whole argument is about.

    ss->ss is horrible, it is indefensible, period.

    In any linked list the previous node is always [struct]->prev and the next pointer is always [struct]->next. Those two things explain exactly what is going on, no confusion it is crystal clear to anyone reading the code.

    Writing struct->next != null might take a few more keystrokes but is is crystal clear, leaves nothing to chance and on top of that it takes no more work for the RTL and I might be mistaken but I think it takes a few less instruction cycles. Although I have never bothered to look at the generated code from the compiler, my guess is that the end result is no different from using the idiom of var++ -v- var = var + 1.

    --
    Hey KID! Yeah you, get the fuck off my lawn!
  134. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    ever heard of list_for_each, list_for_each_entry, list_for_each_entry_safe and the awesome linux/list.h?

  135. Re:Some of the complaints aren't valid by tomhudson · · Score: 1

    The implementation details should be hidden in the function call. This way, risk() is free to either check a variable to see if the value has already been calculated, or do the calculation itself.

    Example (sorry for the non-tabbed formatting): risk() {
    current_risk != NULL ? current_risk : calcCurrentRisk();
    }

    This also lets you have other parts of the code invalidate current_risk, so the next time you call it, it updates the value. Doing the calculation every time can be a waste of time.

    When I'm really stuck for an expressive variable or object or function or method name, I break out the thesaurus. I'd rather spend 10 minutes really thinking about what I'm trying to do, and get the right name, than pick the wrong one and have to "remember" that it's not exactly what it implies.

  136. Re:Some of the complaints aren't valid by Krahar · · Score: 1

    If you can't write and manage a simple link list, a stack, a queue, and proper memory allocation in both c99 and c++, you should go back to java and leave c programming to c programmers. The guy who wrote the original article is a java programmer - look at the complaints and the references he provides.

    Any kind of programmer at all can do trivial tasks like a linked list, a stack and a queue. The simple fact is that if you are paid anything above minimum wage, you are absolutely wasting your time doing so when there are perfectly good libraries that do this sort of thing very well. This has some rare exceptions where none of the available libraries are appropriate, and the key word there is rare.

  137. Re:Some of the complaints aren't valid by tomhudson · · Score: 1

    Okay, those are horror stories - and I can believe the "create multiple directories" one - and not just with directory creation. What's really bad if it doesn't create all the directories, doesn't notice, tries to change to the new directories, then goes on to create its' temp files ... and delete every file in the directory when done.

    No, it wasn't me, but it could have been. Sometimes you're just too rushed to check everything.

  138. Re:author seems somewhat confused and inexperience by Jaime2 · · Score: 1
    Actually, I think the reason he thought it was hard to read was the loop termination condition. "ss" is vague and it is not trivial to arrive at the conclusion that this loop runs until ss is a null reference (for a non-C programmer). Had the loop termination been written as "ss == NULL", then it would have been easy to read. In my experience, C programmers tend to value terseness over readability. The ultimate example of this paradigm is Perl, which we all know can be a nightmare to maintain.

    In my opinion, if that for loop were only a few lines long, the naming would be acceptable. If the loop were 100 lines long, I'd ask for a more descriptive variable name. I use "for(i=0; i<something; i++)" all the time, if it is a very small loop and the usage is obvious.

    As for...

    The culture he's been inculcated in is one in which you never have to understand how a linked list is actually implemented, because you just use a library for it.

    ... I prefer to think that in OOP systems, we hide the implementation of the loop not to pretect our fragile brains, but to not bind the code that uses the list to a specific list implementation. I like being able to switch between ArrayList, HashTable, SortedList, List<Stuff>, and Dictionary without breaking my iteration code.

  139. Re:Some of the complaints aren't valid by Anonymous Coward · · Score: 0

    OK, dimbulb, what is this code supposed to do:

    if ( test )
            do_something(); /* don't forget this! (see DR 1234) */
            do_something_else();

    Familiar patterns - like ALWAYS using brackets - are NOT clutter. You need to get off your faux-sophisticated, misinformed, pedantic high horse and learn how the most powerful tool used to program computers - the human brain - actually works. And then learn to write your code in ways that work WITH your brain's natural abilities.

    Also, you NEVER should use tabs instead of spaces for indentation. What happens if someone happens to use an editor that expands tabs to something different so that code no longer lines up?

    You always use the same editor? With nice, controllable GUI interfaces?

    Well, then you're nobody.

    Because until you're the guy on call who has to be able to fix things over a satellite link with 500 ms RTT and no bandwidth, you won't know why you have to write code so it's consistent no matter what editor you view it in.

  140. Re:author seems somewhat confused and inexperience by ratboy666 · · Score: 1

    "hideously idomatic"

    Actually, the construct is rather pleasant. I now know that if s is a pointer, ss is a traversing pointer, at least in a singly linked list context. Use of ss outside of a "for" or "while", and initialization from anything but an "s" should raise alarms.

    So, I can infer what pp would mean, if I came across it.

    All this from a SINGLE STATEMENT. Wow, to C coder, this IS reasonable code! Not so much to someone new at the game, though.

    As to NULL being zero... that is simply a precondition of the language itself. This is C code, for gods sake! It's not Java. Idioms. Deal. I wonder what happens when these programmers see level 88 Cobol declarations, or FORTRAN equivalence statements, assigned goto, or arithmetic ifs, or even a recursive formulation in C! My, I am getting giddy thinking about the reaction.

    On the other hand, this lack of experience is good for me. I just made some money modifying some COBOL CICS code. Because I can.

    Now,

    "for (currentNode = list->firstNode; currentNode != NULL; currentNode = currentNode->nextNode)"

    does NOT mean

    for (ss = s->ss; ss; ss = ss->ss)

    At least, not until you add

    #define firstNode nextNode

    into your program. Which WOULD raise a WTF!? moment for a lot of programmers. Also, The Fine Article also recommends using STL. In C code. Instead of int ***values; Really. Now, I am not sure what context you would find int *** in. In 30 years of C code, I have yet run across this. But, just how do you retrofit STL into C code that old?

    And now on to the "incomprehensible"

    s->ss->dc.d->v + i

    Well, you can't have an ss without an s (see the first part of my comment), thus s->ss

    Within that, we have a dc, which is (most likely) a union. To save memory. Probably a "context", but I'd actually need a few more lines...

    Choose d, which is a pointer, v (likely "value") because we are adding a local integer.

    Really, the author IS just inexperienced. Problem is, he has a blog and seems to believe in preaching. He takes a joke at face value -- and doesn't think of the real reason...

    I condemn him to coding on an 80x24 terminal, in C 89 (or K&R C), or FORTRAN IV for two years... After which he should revisit this article.

    --
    Just another "Cubible(sic) Joe" 2 17 3061
  141. Buy the books by Anonymous Coward · · Score: 0

    There are many books on the subject.

  142. Re:Some of the complaints aren't valid by ratboy666 · · Score: 1

    We are talking about MAINTAINING code. Not writing new code.

    Standard C did not come with a linked list, stack or queue library. Suck on that fact. If your job is to maintain a such a program, you really have to come to grips with this.

    --
    Just another "Cubible(sic) Joe" 2 17 3061
  143. Re:Some of the complaints aren't valid by Anonymous Coward · · Score: 1, Insightful

    I look at the language standard. Look at the if() statement. It is followed by one line, and a semicolon. No parenthesis. Parenthesis allow you to group multiple lines (blockify) - and its' always possible to replace any block of code with a one-liner (either a function call, a macro, or even using the comma operator).

    Indent your code properly and you'll never have a problem with parenthesis - and your code will be more concise, thus easier to read.

    Adding brackets increases the visual pollution,

    WRONG.

    It's a familiar pattern that the brain can process much more quickly and correctly. And thus much easier to comprehend than your "on-again, off-again" use of braces that introduces two patterns when there only needs to be one.

    So, from a conceptual perspective, it's YOUR style that's more cluttered.

    and I really hate it when people put the opening brace on its own line - its a waste of a line.

    I'm sure that terabytes of storage would be wasted if you were to write all your code that way.

    NOT.

    Nice to see that you code to make your "folding editor" happy instead of the developers who have to maintain your code.

    Folding editors can handle braces at the end of the line just fine - why can't people? Concise can be clear as well.

    Well, let's see...

    Good fucking God. Because humans aren't "folding editors"!!!!!

    Because the human brain doesn't work the same way a computer does? Because a human brain sees and understands familar patterns faster and more correctly? Thereby making your code "sometimes there, sometimes not there" use of braces confusing at a fundamental level, and conceptually more cluttered than always using braces?

    Do you REALLY expect humans and "folding editors" to work the same?

    And YOU are trying to tell everyone how to write code?

    Wow.

    Just wow, someone who goes off on a rant about coding standards, and can't even defend his preferences without resorting to subjective characterizations like "cluttered"? And wonders why people can't understand code the way and editor can?

    Even nicer to see you post that under your real name. Now I know where to file your resume, if I ever see it.

  144. Re:Some of the complaints aren't valid by turbidostato · · Score: 1

    "Also, you NEVER should use tabs instead of spaces for indentation."

    WRONG!!! You always should use tabs for indentation... PROPERLY!

    "What happens if someone happens to use an editor that expands tabs to something different so that code no longer lines up?"

    This CAN'T happen as long as you are using tabs properly: only on the rightmost side up to the right start of the block. I challenge you to find a situation where properly tabbing leads to misaligning due to changing tab width.

  145. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    You're not correct. The C standard guarantees that:

    (((ss != NULL) && (ss)) || ((ss == NULL) && (!ss)))

    By virtue of the fact that:

    1. A NULL pointer must compare equal to 0
    2. "Boolean" statements are in fact integer statements where nonzero is true and 0 is false
    3. Non-null pointers are not be equal to null pointers

    As for C++, it has true booleans but ints still coerce to bool in the same manner, and therefore by extension pointer types still do.

    If that doesn't work, your compiler is VERY broken. Even if the internal representation of NULL is not bit-pattern 0x00000000 (or however long it is on the target architecture).

  146. For e.g. by mahadiga · · Score: 1

    When I'm coding in C, I adopt the best practices from http://lxr.linux.no/

    --
    I'd like to buy homeland for our 10 million people. http://twitter.com/mahadiga
  147. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    And this is relevant to 99.9% of the software out there how?

    Well, it's pretty much relevant to 100% of kernels in current use - and probably 100% of internal workings on consumer devices. Narrow range of work? hardly.
    Get back to your blinkered Windows world and your .NET apps.

  148. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 0

    And replacing the cute one-liner with clearer (and just as fast, since it compiles down to the same instructions) code:

    p = s->next;
    while(p != NULL)
    {
            p = p->next;
    }

    ps: forget about 'NULL != p'. Only ancient compilers cannot detect inadvertent assignment inside evaluation statements [and a coder using such a construct purposely is certainly beyond help :)].

  149. Glad my code turned you inside-out, noob! by asackett · · Score: 1

    I don't comment much. I figure that if you understand the problem domain, my grammar will suffice... and if you do not understand the problem domain you have no business futzing around with my code in the first place.

    I will curse and mock your name after you've left a position because you've context switched ten times to do work that should have been done in one well designed method, and now I've got a server that is puking because you don't know programming nearly as well as you know how to acquire whore points on slashdot.

    As my grandfather, a noble and stoic man of few words would say, shut the fuck up.

    --

    Warning: This signature may offend some viewers.

    1. Re:Glad my code turned you inside-out, noob! by plover · · Score: 2, Insightful

      There is certainly a happy medium between clear code and inefficient code, but in general clear code wins on two counts. One is program correctness: when I'm reviewing clear code, I am more confident that it will do the right thing and won't cause a bug. The other is maintainability. How much time does a maintainer have to spend to understand the code in order to modify it?

      Both of those are cost avoidance strategies. It generally costs me more to have a developer messing around with complex code than it does in run-time cycles. And a bug or a crash is horribly expensive -- handling a bug means you've got phone calls to support, testing, writing up incident reports, fixing the bug, etc. A crash is way more expensive than inefficient code.

      I'm not saying "I like inefficient code." Far from it -- correctness also includes efficiency. Calling a database with a hundred individual queries from inside a loop because the developer doesn't understand how to process a multi-row recordset is horribly wrong, even though it may "look clear". But the correct version of the code doesn't have to read like a plate of spaghetti, either. Invoking the God of Efficiency doesn't magically give a developer license to write unreadable, unmaintainable code.

      Again, this comment is about code "in general." You also have to consider the problem domain. I work on a business application, with a user typing input and processing it in real time. If some rarely used path of the code makes the user stand there for an extra 62 nanoseconds, it's not a problem to me. I don't care as much about things that change response time by less than a human can perceive (8 milliseconds is the threshold for the response time of a human with extraordinary reaction times.) But if I were working on the primitives inside a graphics rendering engine, something that's going to be called a million times per frame, you can bet I'd value efficiency far higher than readability.

      --
      John
  150. Re:author seems somewhat confused and inexperience by rakslice · · Score: 1

    You realize we're talking about C here, right?

  151. Re:Some of the complaints aren't valid by Anonymous Coward · · Score: 0

    "Also, you NEVER should use tabs instead of spaces for indentation."

    WRONG!!! You always should use tabs for indentation... PROPERLY!

    "What happens if someone happens to use an editor that expands tabs to something different so that code no longer lines up?"

    This CAN'T happen as long as you are using tabs properly: only on the rightmost side up to the right start of the block. I challenge you to find a situation where properly tabbing leads to misaligning due to changing tab width.

    You're ASSUMING the next knucklehead who was to maintain the code knows how to set tab stops properly.

    Since you're entire argument is based on a questionable assumption, it fails.

  152. Re:Some of the complaints aren't valid by tomhudson · · Score: 1

    1. The stl is totally inappropriate for ANY c program - it requires c++.

    2. Sometimes you don't want the overhead of one of those generic one-size-fits-all solutions.

    3. Are those libraries perfect? No? Well, gee, so when there's a bug, that's one more place it might have crawled in ...

    4. Sometimes you want to take advantage of the extensions in c99.

  153. Re:author seems somewhat confused and inexperience by rwiggers · · Score: 1

    Better yet.

    for(p = s->next; p != 0; p = p->next)

    Sure it's more verbose, but it's also more readable especially to a novice, since it's closer to the usual prototype of a for loop. (i =0; i xxx; i++)

    Wrong. You can't assume NULL=0 and have portable code, although it will most probably work.

  154. Re:Some of the complaints aren't valid by tomhudson · · Score: 2, Insightful

    And proper indentation would have saved the day - no braces required.

    It's one thing python actually gets right.

    And your example just shows that a lot of people can't read code. If you're not dependent on braces to "clue you in", you'll spot the error immediately.

    Also, you NEVER should use tabs instead of spaces for indentation. What happens if someone happens to use an editor that expands tabs to something different so that code no longer lines up?

    That's a problem with YOUR editor, not mine. there's a TAB key on your keyboard for a reason.

    One of the reasons people try to use 4 spaces instead of an 8-space tab is because they let their code get fugly - WAY too many levels of indent and way too long variable names - and the only way they can see it on-screen without resorting to havig their code wrap every second line is to cheat - to only indent 4 spaces instead of a hard tab.

    They're too unimaginative to come up with concise descriptive variable, function, class, and method names, and to stupid to realize that when your code has too many levels of nesting, it's "broken by design" and a great place for bugs to breed..

    You always use the same editor? With nice, controllable GUI interfaces?

    Well, then you're nobody.

    Because until you're the guy on call who has to be able to fix things over a satellite link with 500 ms RTT and no bandwidth, you won't know why you have to write code so it's consistent no matter what editor you view it in.

    Arrogant little piss-ant, aren't we? I'm quite comfortable using vim on a remote box via ssh. I was writing code before the terms tui and gui were even in common use - we only had text screens. We had to code by pushing the bytes uphill, both ways, in a storm (well, not quite that bad, but monochrome amber monitors and hercules video cards give you an idea?). And in your example of "no bandwidth", a hard tab is better, since it's only 1 character. So who's the nobody? According to your definition, you failed since you sure wasted bandwidth. Like your examples - but at least you're consistent in that respect.

  155. Re:Some of the complaints aren't valid by tomhudson · · Score: 2, Insightful

    It's a familiar pattern that the brain can process much more quickly and correctly.

    ... only because that's all you've experienced. I have no problem parsing code that removes all superfluous braces around one-line statements, or for that matter, the classical empty for(); statement that does all the work inside the for() statement, so you terminate it with a semicolon, rather than what you would do - put some empty braces. The braces are only required for multi-line blocks in the language standard. If you can't read code that conforms to the standard, then you have the problem, not me.

    I guess you need to learn to be more fluent in the language. Next, you'll say that the comma operator should be banned because YOU might make a mistake in interpreting how it works. Or the hook operator. Or *gasp* those evil macros. And you'll also insist that we use that piece of shit called the stl when we're trying to make a multi-threaded app, and then wonder why performance is absolute crap.

    Good fucking God. Because humans aren't "folding editors"!!!!!

    Really? Next you'll say you can't read the first line of a paragraph, then skip to the next paragraph if you realize that what you're not looking at the right code. Do you move your lips when you read?

    Look, if YOU have a problem with concise code, that's your problem. Your style went out back in the early '90s. It's still taught that way because teachers are inevitably a decade behind the curve - at the minimum. Only old farts who can't adapt, the people who learned from them, people who are trying to increase their LOC count, and old koreans still put the opening brace on its' own line, or are so "un-fluent" in the language that they need to blockify everything, and can't handle something as simple as an if() without braces. What next - putting braces around the contents of case statements "just in case"? I've seen people do crap that, and it tells me one thing - they don't really know c. For them, pascal is probably a better option, since you HAVE to put begin and end ...

    Visual conciseness isn't a question of saving disk space - it's a question of making the code easier to read by reducing clutter. It works - problem is, you're so used to the crutch (yes, all those superfluous braces that the standard says aren't required ARE a crutch) of the clutter that you can't do without it. You're a crip. Admitting it is the first step in overcoming your handicap.

  156. Re:Some of the complaints aren't valid by AmiMoJo · · Score: 1

    Make should be redundant, i.e. it should be possible to write software without having to hand edit a complex script that does nothing other than tell the computer how to put all the parts together.

    --
    const int one = 65536; (Silvermoon, Texture.cs)
    SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
  157. Re:author seems somewhat confused and inexperience by Anonymous Coward · · Score: 1, Informative

    > Wrong. You can't assume NULL=0 and have portable code, although it will most probably work.

    You can if it's ANSI C. The standard dictates:

    6.3.2.3 Pointers

    3) "An integer constant expression with the value 0, or such an expression cast to type
    void *, is called a null pointer constant. If a null pointer constant is converted to a
    pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal
    to a pointer to any object or function."

    If p is a pointer type, "p != 0" should always work equivalent to a null pointer.

  158. Re:Some of the complaints aren't valid by TemporalBeing · · Score: 1

    I look at the language standard. Look at the if() statement. It is followed by one line, and a semicolon. No parenthesis. Parenthesis allow you to group multiple lines (blockify) - and its' always possible to replace any block of code with a one-liner (either a function call, a macro, or even using the comma operator).

    Wrong. Such code is just waiting for the following to happen:

    #define f(x) (x = x / 3.1459)
    ...
    #define f(x) ( x = g(x); x = x / 3.1459)
    ...
    if (object.type() == "circle")
    f(object.radius);
    ...

    Guess what that if statement will look like to the compiler? Brackets are very much better to use and make code clearer to both the programmer and the compiler for what is going on.

    if (object.type() == "circle")
    object.radius = g(object.radius);
    object.radius = object.radius / 3.1459;
    ...

    #define f(x) (x = x / 3.1459)
    ...
    #define f(x) ( x = g(x); x = x / 3.1459)
    ...
    if (object.type() == "circle")
    {
    f(object.radius);
    }
    ...

    Note: While this situation specifically points out the issue with Macros, which are the most susceptible to it - it is by no means the only reason. Just one point why you got it wrong. And I am in no way saying that Macros are not good to use - sometimes they are, most of the time they are not.

    --
    Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
  159. Easy rule of thumb for optimization by n7ytd · · Score: 1

    Just ask yourself: which is more valuable, the programmers' time, or the computer's time?

    When your processor's running at 2GHz, optimizing a loop to squeeze 4 million instructions into 3.4 million instructions saves the computer less than 1/10 of a second, while costing the programmer how many minutes? At that's a generous guess, assuming that your compiler can't do a better job of optimization that the programmer, anyway.

    In most cases, every programmer trying to learn your code (and that includes you, 4 weeks after writing it) is better served by making it as dead-simple-easy to understand as possible than trying to shave instructions.

    Of course, then there are the special cases; if that loop is going to be run 500 times a second, then maybe the computer's time is starting to get more valuable, and shifts the calculation in its favor. Then the real question isn't when to be clever, but knowing how to measure that.

  160. Re:Some of the complaints aren't valid by TemporalBeing · · Score: 1

    You assume wrong. I've had to correct code because people coming from the Windows world NEVER turn on warnings. Many don't even know how to edit a make file. If there's no clicky thingee, they're lost.

    This is mostly b/c Microsoft (in their infinite wisdom) only enables Warning Level 1 by default, which catches almost nothing. Now it's not hard to turn on Warning Level 4, but then you also have to go through and fix all the stuff and learning which warnings to ignore from Microsoft's code - headers, etc. - that gets brought in. It's bad enough using MS APIs can cause memory leaks (my favorite being one that caused a 4 byte memory leak whenever used - and no, it there wasn't anything I could do to clean up anything to resolve it at my program's level; only a memory stack analysis was able to find what it was; may be they fixed this for Win7/2k8 with the refactoring they did...hopefully.)

    Thankfully I'm mostly doing Qt development now...:->

    --
    Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
  161. Re:Some of the complaints aren't valid by TemporalBeing · · Score: 1

    Java is always interpreted - sure, at runtime, it does "just-in-time" compiling and caching of byte-code - but it has to INTERPRET that first. You can't keep the cache between program runs, for security reasons.

    Please see the GNU Java Compiler. To quote from the site:

    GCJ is a portable, optimizing, ahead-of-time compiler for the Java Programming Language. It can compile Java source code to Java bytecode (class files) or directly to native machine code, and Java bytecode to native machine code.

    99% of the time yes, Java is JIT compiled to native code. But there are ways to binary compile it. (BTW, I too hate Java.)

    --
    Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
  162. Re:Some of the complaints aren't valid by turbidostato · · Score: 1

    "You're ASSUMING the next knucklehead who was to maintain the code knows how to set tab stops properly."

    So, in order for others no to impose you their "standard" tabstop your proposition is to impose everybody *your* "standard" tabstop?

    And about knuckleheads, if you accept them disorganizing your source code, what will be next? Allow those knucleheads to write your source code? *That* is the real failure.

  163. essence vs ceremony by ZenDragon · · Score: 1

    In my opinion this matter comes down to a balance of essence and ceremony in code. Essence is that much actual provides a function (business logic), and ceremony is simply that which we constantly repeat (program logic; i.e. error catching blocks, etc). One elegant one liner may provide essence in the code but at the loss of the ceremonial code that makes that code usable and easy to follow/maintain Personally I find the a best practice to maintain separation of those two elements such that ceremony can be mapped in through a defined path, without being overly verbose. In other words, keep your business logic separate from program logic.

    In good practice this will help coders avoid the need for clever one liners so long as the business logic doesn’t interfere with the program logic. In some cases when a clever one liner may be required they are only in the business logic and shouldn’t interfere with the program thus making it much easier to folllow without having to trace it all over the place.

    An example of this may be using a lambda invocation pattern to wrap error catching around a database factory implementation such that all calls to the database happen through one interface/class implementation. This allows you to change the business logic without touching ANY of the program code. I hope that makes sense, and I hope Im not misunderstanding the question either! lol

  164. Re:Some of the complaints aren't valid by badkarmadayaccount · · Score: 1

    I think the word you are looking for is compiled, and there have been AOT compilers for Java a long time. Also, the compilation overhead for any non-trivial application is generally negligible. And who says you can't cache compilations? What, OS not secure enough? Not my problem.

    --
    I know tobacco is bad for you, so I smoke weed with crack.
  165. Worst documentation ever! by Anonymous Coward · · Score: 0

    You know what is the most horribly documented code in the history of the world? DNA

  166. Simple compilers may be to blame by amn108 · · Score: 1

    Clever solutions is a tool in the hands of a programmer who uses a compiler that cannot do the clever job itself. This is currently, most of all compilers/translators out there and more importantly, most of the "widely-used" (an oxymoron!) ones. In other words, if your compiler is stupid, it is your job to produce the optimization by altering readable code into code that performs efficiently but looks too funny. Maybe languages like Haskell or ML will liberate us from this. It is a culture, a culture that lacks education.

    Always rely on the compiler. It is your translator, and as with any good translator, you can relax speaking your native language (i.e. human) and trust it to do more an adequate job.

  167. Re:Some of the complaints aren't valid by ThirdPrize · · Score: 1

    I agree!

    --
    I have excellent Karma and I am not afraid to Troll it.
  168. Re:Some of the complaints aren't valid by jgrahn · · Score: 1

    #define f(x) (x = x / 3.1459)
    ...
    #define f(x) ( x = g(x); x = x / 3.1459)
    ...
    if (object.type() == "circle")
    f(object.radius);
    ...

    Guess what that if statement will look like to the compiler? Brackets are very much better to use and make code clearer to both the programmer and the compiler for what is going on.

    I use if() {...} brackets because my readers expect it. That's enough reason. We have all kinds of crappy bracket positioning and indentation styles, but the brackets are always there (except in some special pattern cases). As for your example:

    • Noone in his sane mind does multi-statement macros like that. Wrap them in a do { ... } while(0) and the problem goes away.
    • This is 2009. Inline functions have existed in C++ for decades, and in C since 1999. You don't have to use macros a lot these days.
    • And if you do, you name them FOO rather than foo, so people understand that something funny is going on.
    • Your macros are broken anyway ... side-effects of evaluating (x) ... lots of fun. (Yes, I know those macros were probably just quick examples.)
  169. Re:Some of the complaints aren't valid by TemporalBeing · · Score: 1
    That doesn't negate the fact that people do do that, and have done it.

    But the greater point is, that when maintaining code something small can have a big effect on the program as a whole. Get someone who doesn't know much about macros, and the problem explodes - especially when you have a program where (for whatever reason) you can't replace the macro with an inline function (and there are cases, though rare).

    Also, while I've read a lot of macros - I've never seen anyone wrap it in a loop like you suggest. More likely than not macros are written as follows:

    #define macroFunction(a,b,c) \
    (c = sqrt(a*a+b*b))

    #define macroFunction2(a,b,c) \
    { \
    b = (c*b + b*a)/(a*c); \
    }

    --
    Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
  170. Anonymous Coward by Anonymous Coward · · Score: 0

    http://www.jlab.org/~saw/linux/lug_19091999.mgp
    What is this?

  171. Re:author seems somewhat confused and inexperience by toddestan · · Score: 1

    "Most of the variables in CRAP are one or two letters long. Originally, this was due to the memory constraints involved when programmers first designed and built the system." This is not particularly plausible. C is a compiled language, so using long variable names has no effect on the amount of memory used at run-time. It would also have been more or less a non-issue in terms of RAM used at compile-time. C only dates back to 1972, and didn't start to get popular until ca. 1980. By that time, using long variable names would have had a pretty negligible effect on RAM used by the compiler in proportion to total available RAM. And in any case, if compiles are taking too long, you just break up your files into smaller parts.

    You also need to take into account the space the .c file is going to take before it's compiled too. I just took a look at a smallish program I made, consisting of about 3800 lines of source. It's 108k, which is not a trivial amount of ram on a computer from the early-mid 1980's.

  172. Whats clever to some is ordinary to others by Anonymous Coward · · Score: 0

    often people who complain about hard to follow code are simply poor performers. I've had people complain about this and then go ask 4 others what the code did and they all answered after looking at the code for 60 seconds. So obviously it was not the code....

    What happens when you get one of these types and you actually listen to them. You end up with code that spans 4 pages instead of 1 page. Then take that same code to other people and time them on how long it takes them to understand it. Time will double.

    So really if people start complaining about tricky code, then you have to take a long hard look at them. I personally can't think of ANY code I found to be tricky unless it was in a contest for that purpose. I have spent much more time examining code that should have taken seconds to look at rather than the minutes it did because it was part of a overall design philosophy involving a layered approach etc.

  173. Re:Some of the complaints aren't valid by Anonymous Coward · · Score: 0

    writing c code
    designing in c or c++
    leave c programming to c programmers

    "C", "C++".