Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Programming

Defining Useful Coding Practices? 477

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

Defining Useful Coding Practices?

Comments Filter:
  • Simple... (Score:5, Insightful)

    by Anonymous Coward on Sunday December 06, 2009 @11:57AM (#30343510)

    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.

    • Keep it simple (Score:5, Insightful)

      by yog ( 19073 ) * on Sunday December 06, 2009 @12:22PM (#30343646) Homepage Journal

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

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

        • 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()

          Peopl

          • Re: (Score:3, Insightful)

            by Toonol ( 1057698 )
            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.)
        • by AmberBlackCat ( 829689 ) on Sunday December 06, 2009 @12:57PM (#30343888)

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

          • Re: (Score:3, Interesting)

            by tomhudson ( 43916 )

            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 o

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

            W

        • by Graff ( 532189 ) on Sunday December 06, 2009 @01:37PM (#30344188)

          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.

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

        by UnknownSoldier ( 67820 ) on Sunday December 06, 2009 @01:12PM (#30343986)

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

        • Re: (Score:3, Interesting)

          by Simon80 ( 874052 )
          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.
        • Re: (Score:3, Insightful)

          by w3woody ( 44457 )
          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".
      • by Twinbee ( 767046 )

        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.

    • Re:Simple... (Score:5, Insightful)

      by Coryoth ( 254751 ) on Sunday December 06, 2009 @12:24PM (#30343662) Homepage Journal

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

    • by Z00L00K ( 682162 )

      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 b

    • Re: (Score:3, Interesting)

      by camperdave ( 969942 )
      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 m
    • 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

    • 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

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

  • multiple revision? (Score:2, Insightful)

    by leuk_he ( 194174 )

    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.

    • by joaommp ( 685612 )

      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 all

    • Re: (Score:2, Informative)

      by daedae ( 1089329 )

      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.

    • Re: (Score:3, Insightful)

      by Toonol ( 1057698 )
      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
  • by John_Sauter ( 595980 ) <John_Sauter@systemeyescomputerstore.com> on Sunday December 06, 2009 @12:00PM (#30343530) Homepage

    To my mind, the best coding standard is Don Knuth's Literate Programming: http://www.literateprogramming.com/ [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.

    • by CortoMaltese ( 828267 ) on Sunday December 06, 2009 @12:21PM (#30343634)
      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".

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

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

    • by joaommp ( 685612 ) on Sunday December 06, 2009 @12:37PM (#30343736) Homepage Journal

      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.

      • by joaommp ( 685612 )

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

        • by John_Sauter ( 595980 ) <John_Sauter@systemeyescomputerstore.com> on Sunday December 06, 2009 @01:16PM (#30344012) Homepage

          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.

          • by joaommp ( 685612 )

            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.

      • by lophophore ( 4087 ) on Sunday December 06, 2009 @01:48PM (#30344252) Homepage

        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.

      • Re: (Score:3, Insightful)

        by Alomex ( 148003 )

        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

  • 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 l
  • Subs and functions (Score:3, Interesting)

    by A Friendly Troll ( 1017492 ) on Sunday December 06, 2009 @12:04PM (#30343546)

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

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

        • by dodobh ( 65811 )

          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

        • by Graff ( 532189 )

          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 stre

    • by AB3A ( 192265 ) on Sunday December 06, 2009 @12:40PM (#30343770) Homepage Journal

      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.

  • by djpretzel ( 891427 ) on Sunday December 06, 2009 @12:04PM (#30343550) Homepage
    "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.
    • by nietsch ( 112711 )

      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.

  • by johnlcallaway ( 165670 ) on Sunday December 06, 2009 @12:06PM (#30343556)
    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.
    • by mclearn ( 86140 )
      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,
    • by mveloso ( 325617 ) on Sunday December 06, 2009 @01:19PM (#30344042)

      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.

  • Review the Code (Score:5, Insightful)

    by RAMMS+EIN ( 578166 ) on Sunday December 06, 2009 @12:06PM (#30343562) Homepage Journal

    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.

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

  • 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
  • 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 manage

  • by WoodstockJeff ( 568111 ) on Sunday December 06, 2009 @12:19PM (#30343622) Homepage

    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!

    • Re: (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.

      • by tepples ( 727027 )

        Learn to use autocomplete.

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

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

      • by js_sebastian ( 946118 ) on Sunday December 06, 2009 @04:30PM (#30345576)

        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.

    • by Jeremi ( 14640 )

      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 sho

    • by James Youngman ( 3732 ) <jay.gnu@org> on Sunday December 06, 2009 @02:56PM (#30344840) Homepage

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

  • 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 e

  • by jtolds ( 413336 )

    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

    • Re: (Score:3, Informative)

      by gbjbaanb ( 229885 )

      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 [reviewboard.org] which is more source-control tool neutral (requires python) and can be automated according to your SCM tool.

  • by Kartoffel ( 30238 ) on Sunday December 06, 2009 @12:34PM (#30343726)

    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.

    • by lytles ( 24756 )

      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

  • by noidentity ( 188756 ) on Sunday December 06, 2009 @12:37PM (#30343740)
    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.
  • 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.

  • 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
  • Rule of thumb (Score:5, Insightful)

    by xororand ( 860319 ) on Sunday December 06, 2009 @12:39PM (#30343766)

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

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

  • 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 squ
  • by bcrowell ( 177657 ) on Sunday December 06, 2009 @12:50PM (#30343838) Homepage

    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.
    • by Anonymous Coward on Sunday December 06, 2009 @02:31PM (#30344638)

      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.

    • by hey ( 83763 ) on Sunday December 06, 2009 @02:55PM (#30344830) Journal

      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)

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

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

  • Too MUCH of this (Score:3, Insightful)

    by omb ( 759389 ) on Sunday December 06, 2009 @12:59PM (#30343900)
    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#.
  • 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,
  • Teams (Score:5, Insightful)

    by jlowery ( 47102 ) on Sunday December 06, 2009 @01:02PM (#30343918)

    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.

    • by michaelmalak ( 91262 ) <michael@michaelmalak.com> on Sunday December 06, 2009 @02:03PM (#30344372) Homepage
      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."

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

  • 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 i

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

  • by presidenteloco ( 659168 ) on Sunday December 06, 2009 @01:20PM (#30344050)

    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.

  • elegant != clever (Score:5, Insightful)

    by dsoltesz ( 563978 ) <deborah.soltesz@gmail.com> on Sunday December 06, 2009 @01:36PM (#30344178) Homepage Journal

    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.

  • A fool's errand (Score:5, Insightful)

    by ClosedSource ( 238333 ) on Sunday December 06, 2009 @01:42PM (#30344216)

    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.

  • Code editors (Score:3, Interesting)

    by arjan_t ( 1655161 ) on Sunday December 06, 2009 @04:24PM (#30345546)

    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.

  • by Sarusa ( 104047 ) on Sunday December 06, 2009 @05:54PM (#30346218)

    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?

"What man has done, man can aspire to do." -- Jerry Pournelle, about space flight

Working...