Forgot your password?
typodupeerror
Programming IT Technology

Are You Proud of Your Code? 682

Posted by Zonk
from the code-poets-speak-up dept.
An anonymous reader writes "I am downright embarrassed by the quality of my code. It is buggy, slow, fragile, and a nightmare to maintain. Do you feel the same way? If so, then what is holding you back from realizing your full potential? More importantly, what if anything are you planning to do about it? I enjoy programming and have from a young age (cut my teeth on BASIC on an Apple IIe). I have worked for companies large and small in a variety of languages and platforms. Sadly the one constant in my career is that I am assigned to projects that drift, seemingly aimlessly, from inception to a point where the client runs out of funding. Have any developers here successfully lobbied their company to stop or cut back on 'cowboy coding' and adopt best practices? Has anyone convinced their superiors that the customer isn't always right and saying no once in awhile is the best course of action?"
This discussion has been archived. No new comments can be posted.

Are You Proud of Your Code?

Comments Filter:
  • by suso (153703) * on Monday December 10, 2007 @09:12AM (#21640631) Homepage Journal
    One thing to keep in mind when determining the quality of your code is that other people will most likely criticize the quality of your code. Usually saying that it sucks, when usually its just the person having their own way of doing things. I don't know why this is, I think its just human nature.

    I've seen time and time again programmers taking over for other programmers' code and saying that the previous person's code sucks. Its like a right of passage or something.
    • by DeeQ (1194763)

      One thing to keep in mind when determining the quality of your code is that other people will most likely criticize the quality of your code. Usually saying that it sucks, when usually its just the person having their own way of doing things. I don't know why this is, I think its just human nature. I've seen time and time again programmers taking over for other programmers' code and saying that the previous person's code sucks. Its like a right of passage or something.

      In most of my experiences its not their coding that sucks its their lack of comments or poor commenting that makes their code suck.

      • by SilentBob0727 (974090) on Monday December 10, 2007 @11:22AM (#21642127) Homepage
        Over-commented code (the kind where there's 2-3 lines of comments for every one line of code -- not every closing brace needs a reminder that we're exiting a code block, thanks!) is pretty awful too. I've met people of the agile variety who insist that well-written code needs no documentation: that if you carve your code up into small, tight, appropriately named classes and methods it becomes obvious what your code does and your code becomes "self-documenting", and I've met people who won't even look at code unless every single line is commented telling them precisely what it does, so "int i = a + 2;" has to have a comment above it saying "// create a signed 32-bit integer variable, i, and assign it two more than the value of a".

        The former is wrong because while it's great that we now know what each little piece of your code does, it's still a challenge to see the forest for the trees in all but the most trivial cases (it also means that after several refactors you end up with a whole lot of miniature orphaned functions littering up your code that are never called and that do nothing but that everyone's afraid of deleting). A good method name doesn't tell the reader why the method is there or what its intended usage is. The latter is wrong as well, because suddenly naturally flowing code is broken up to the point where comments become a distraction and make the code harder to read (incidentally, this is why I started using justified end-of-line comments... it helps with the distraction).

        You should always comment your classes (or your data structures if you're using a non-object-oriented language) -- state the reason they exist, what requirement they fulfill, their role in the application, and any caveats to using them. Comment your constants, class and instance variables if it's not bleedingly obvious from the class description what purpose they serve.

        Comment your public methods! Your public methods are essentially the exposed API into your code, so if you want your successor reusing code you wrote rather than writing his own that does the exact same thing, it had better be absolutely clear how it is to be used. At a minimum, this should include what the method is there to do, a detailed description of each parameter to the function, and any constraints on the parameters, side effects of invoking the method (Does it write to any files? Set any external variables? Allocate or free any memory?), the range of values that can be returned, a description of any special return values, and any exceptions that can be raised when calling the function. Comment your private methods as well, though with your private methods you may be justified in just explaining why the method is there.

        And for the love of God, don't comment your private variable accessors unless they get or set in an unusual manner. And you don't have to comment constructors that just assign parameters to instance variables.

        Finally, while those agile guys are right in that your code really should have a natural flow and speak for itself, you should still comment your runtime code. Longer functions should be divided up into "paragraphs" with comments stating what's about to happen and how the current state contributes to the overall goal of the function. If your functions have extremely clean divisions of functionality, consider breaking them up into smaller private functions unless you're concerned with every last ounce of performance and can't afford the 10-20 cpu cycles necessary to do a function call (or declare the methods as inline). If you're doing something in a manner that's unorthodox or not immediately readable or that will make someone reading your code go, "what the hell?", either rewrite it (=D) or comment it to justify why you feel it was necessary to do it that way.

        Automated unit tests can also be a good supplement to well-documented code, as they give natural examples of code usage and can serve as tutorials for people trying to learn your code. Often this displays intent a lot better than comments can, since doing is often more effective than saying.

        I find people are more concerned with whether code is commented "enough". I think it's better to be concerned not with the amount, but the quality of comments.
        • by mini me (132455) on Monday December 10, 2007 @11:54AM (#21642609)

          # Les gars sont agiles droite. Si le code est écrit Bien, il va parler pour lui-même.
          # Il n'ya pas besoin de Double emploi avec ce que dit le code dans une autre
          # langue (Anglais). C'est peu comme votre commentant Anglais paragraphes d'une
          # interprétation française. À moins français est votre langue maternelle c'est
          # juste aller Pour obtenir de la manière et de rendre la lecture de la même Anglais
          # Plus difficile. Comme un programmeur, c'est mon travail d'être Parle couramment le
          # langage de programmation de mon choix. Reading Code devrait être aussi simple que de lire un livre.
          The agile guys are right. If the code is written well, it will speak for itself. There's no need to
          duplicate what the code says in another language (i.e. english). It's kind of like commenting your
          english paragraphs with a french interpretation. Unless french is your native tongue it's just going
          to get in the way and make reading the english even more difficult. As a programmer, it's my job to
          be fluent in my programming langauge of choice. Reading code should be as easy as reading a book.

          # Cela dit, parfois, vous avez vraiment à écrire Quelque chose d'anormal, et, dans ce cas, vous devriez
          # Commentaire. Toutefois, ces cas sont rares Entre.
          That said, sometimes you really do have to write something abnormal, and in those cases you should
          comment it. However, those instances are few and far between.
          • by SilentBob0727 (974090) on Monday December 10, 2007 @12:25PM (#21643097) Homepage
            This is a false analogy. Human language is symmetric in that it is designed to be produced and consumed by a human. Programming languages, on the other hand, are asymmetric in that regard. As such, reading a computer program requires a certain amount of aptitude that's better suited to a computer -- for example, tracking the entire program state at any given time. Granted, you only have to track the state that's relevant to the current context, but recursively switching contexts (see function call, go look up function, finish reading function, go back to function call, keep reading previous function) is something a computer does well and a human doesn't do well.

            Also, humans tend to read left-to-right, top-to-bottom. Any worthwhile program is filled with loops, branches, conditionals, calls, recursion, etc. As the program size grows, it becomes very difficult to sit down with the uncommented code and just read it, and actually take away the general gist of what was just read. To do so requires several sessions of hard concentration and focus, and time to reflect on and digest how it all works together. Well-structured, well-written code can only go so far.

            Comments, in many cases, make up for that lack of aptitude. It's not restating, it's clarifying what the code does so as to make it less likely for the reader to get lost and help speed up the learning curve.
          • by IngramJames (205147) on Monday December 10, 2007 @02:10PM (#21644909)
            The agile guys are right. If the code is written well, it will speak for itself. There's no need to
            duplicate what the code says in another language (i.e. english).


            Some of the time, that is correct. Most of the time, it isn't. But that's just in my field (financial software). There are two languages in use in the software I write and maintain: "code", and "business". It is vital, in my area, that code is commented well, to explain the business reasons behind the code. Small loops sometimes speak for themselves and don't need commenting. For example, a method called "getAllCashSecuritiesForAccount", if it contains only a simple loop, doesn't need commenting.

            But because developers come in who don't have a financial background, and don't know their way around the system, comments in the code are essential. It helps them understand both the code they are looking at, and the business flow.

            But the main reason for having clear, concise comments in the code is so that you don't have to read the code. For example (apologies for the VB):

            'get the securities in the current scope
            avItems = dctSecurities.Items
            for nCtr = 0 to dctAllSecurities.Count-1
                Set oSecurity = avItems(nCtr)
                If oSecurity.CurrentScope = enScope Then
                      colScopeSecurities.Add oSecurity
                End If
            Next nCtr

            ' Apply the change to each security in turn - if they have the relevant settlement currency
            dTotal = 0
            For each oSecurity in colSecurities
                If oSecurity.SettlementCCy = sCCy Then
                    oSecurity.MakeAChange dNewValue
                    dTotal = dTotal + oSecurity.MarketValue
                End If
            Next oSecurity

            ' Handle case of account going short
            If dTotal < 0 then
                  oAccount.HandleShortChange
            End If



            The above comments are all aligned. They appear in the IDE in a different colour. They are written in plain English. They are clear and concise. If I am looking for a bug which involves the total value which has changed being wrong, then from scanning 3 lines, written in plain English, it is fairly clear where I should start my search. Yes, given a few more seconds, I can read through the whole code, and see what is being done. But it's quicker and easier to read 3 lines of English than 15-odd lines of code, which aren't aligned.

            In fact, possibly the most useful aspect of comments like the above are to eliminate all the code you don't need to read.

            You could argue, of course, that the above could be broken down into 3 seperate methods, all clearly named. But I think that's overkill. This is a simple method, doing three simple things. I ought to be able to read it all the way through without having to flip between three different methods, which exist only to save the developer taking the time to type some clear comments.

            Lastly: yes, I am aware that the above code performs two seperate iterations of the same objects, and is terribly inefficient; it is for illustrative purposes only, and on no account should be treated with any seriousness :)
          • by nahdude812 (88157) * on Monday December 10, 2007 @04:11PM (#21646593) Homepage
            There is too often a difference between what a block of code does and what it is supposed to do. Code comments can indicate the intention of a block of code. This is a big deal, because I see code which passes test cases all the time, but which don't work as intended especially under exception circumstances (what if the arguments were a value other than what was expected).

            Plus sometimes you can understand each operation in the code block but not know what it does. Have you ever looked at an MD5 implementation? You need a comment that tells you what it does in general terms even though you know what it does in specific terms.

            I believe in making my code self documenting as much as reasonable, but any time I'm not simply reading data and outputting it (or reading data and inputting it), a backup comment describing the purpose both makes it easier to read and to maintain.
        • Re: (Score:3, Insightful)

          by oliverthered (187439)
          hmm.. I tend more to the Agile way typically my comments look like: // Add a beginning and end of line match (this may be a bad thing? still needs to be thought about/worked out properly)
          #warning "This call fails in .net 1.1 because of a bug in .net 1.1, the easiest way around it is to use .net 2"
          I also put short comments in about each 'paragraph' block in the code and plenty of TODOs where work still needs to be done or extra features could be added.

          I do also write fairly full design documentation as I go
        • by Fross (83754) on Monday December 10, 2007 @12:27PM (#21643159) Homepage
          I am one of those people who likes lots of code. So much so that I've developed a style, similar to how I used to code 68k assembler, of running comments down a second column (usually 40-60 characters in) that describes what is going on. After all, it doesn't interrupt the flow of the code, and if you're editing Java on an 80-column fixed-width interface, you're doing it wrong to begin with. I wouldn't say I comment every line, probably one in every 3. However, this gripe with over-commenting is fundamentally flawed:

          and I've met people who won't even look at code unless every single line is commented telling them precisely what it does, so "int i = a + 2;" has to have a comment above it saying "// create a signed 32-bit integer variable, i, and assign it two more than the value of a".

          Why on earth would you write a comment like that? That is ridiculous. However, the line DOES need a comment. It's declaring a variable with a non-descriptive name and doing something specific with it. Now, the comment should do something like say what the variable is used for, if it's non-obvious. In this case, "int i" is usually used for loops, so it doesn't need a comment unless it's *not* used for loops. :) However, if it was being used in a loop, why is it being set to a+2? Is a some sort of offset in an array? Is it a user-entered value? THIS is what the comments will illustrate, eg:

          int i = a + 2; // skip the first two elements in the loop as they contain other data

          or

          int i = a + 2; // user input will be off by 2 because of (strange reason here)

          writing comments like "initialise variable" is useless, but thinking that may be all there is shows a misunderstanding about how comments work.

          You can assume the person reading your code is a programmer, familiar with the language used, and able to follow general program flow. However, he may not be familiar with the rest of the system, nor with any specific tricks you may use[1]. Comments should be like a director's commentary on the code, pointing out what may not be obvious, and giving the bigger picture - the reason why a specific variable is used a certain way, or what a messy few lines of code may be achieving, eg: // now split the input into an array and parse ready to give to the file handler
          (horrible loop declaration here)
          (even more horrible regex here)
          (custom function calling here)

          It's said comments are like sex - even when they're bad, they're still pretty good. I'm pretty sure I've never spent 3 hours trying to work out how to get THAT to work, though!

          [1] eg, I use a relatively uncommon trick in Java doing string comparisons of if(!"blah".equals(myString)) because it can't fail on the null pointer check that if(!myString.equals("blah")) can. A simple example, but something more complicated will save someone time if it just has a quick comment next to it saying what that section of code is achieving.
          • Re: (Score:3, Insightful)

            by SilentBob0727 (974090)
            I think we're saying essentially the same thing. I'm arguing for better commenting and learning what kinds of comments are unnecessary.

            I'm griping about comments that triple the size of the source code and disrupt the code's readability, yet say nothing that can't be discerned immediately from the code.

            Comments should describe "what" in only very high-level terms, which is why "what" comments are better suited to method and class level. Beyond that, they should primarily talk about "why", and to a lesser ex
          • by macrom (537566) <macrom75@hotmail.com> on Monday December 10, 2007 @05:09PM (#21647485) Homepage
            It's said comments are like sex - even when they're bad, they're still pretty good.

            No, programming is like sex. Make one mistake and you end up supporting it the rest of your life.
        • by Sparks23 (412116) * on Monday December 10, 2007 @12:38PM (#21643373)
          On the agile, small-functions stuff, there is a reason that agile programming is mostly meant for languages like Java; most agile teams have testing harnesses which will tell them when a small function is no longer used, or how many places a small function is used. This does not solve the 'forest for the trees' problem, but does at least eliminate the fear of deleting small orphaned functions.

          I do otherwise agree with all your points; the best place is a middle ground between agile's self-documenting and the traditional ZOMG COMMENTS. At my (non-agile) workplace, we document at the top of each function what the function does and what it takes and returns, as well as documenting any complex or unintuitive block of code within a function. (The ideal would be to avoid unintuitive code entirely, of course, but this is not always possible when dealing with things like VoIP goo.)
        • by djasbestos (1035410) on Monday December 10, 2007 @01:24PM (#21644137)
          I fully agree. I inherited a LOT of uncommented and shittily commented code, and it is a royal PITA to figure out WHY it is doing what it is doing (which was basically your point). On the other hand, at least with crappy comments, there is occasionally a nugget of useful information...I despise the comment-free code more, but the code itself also looks like it was designed by someone on an acid trip.

          So yes, comments should say WHY more than WHAT (specifically) a line or block of code does. A short narrative is usually the most helpful, ime. Basic description of what the method (or even a crucial line if it's the least bit unconventional or otherwise unintuitive) does (in bird's-eye-view terms / how you would explain it to a non-programmer), and WHY it is doing it if that purpose isn't obvious from WHAT.

          And I also say (most of) my predecessors' code sucks, but in this case, it does. There was one guy who seemed to have a decent idea of what he was doing, and I think he got burnt out by the complete buffoon of an "IT Manager" they had at the time (hurray cronyism! He still works here in his own project group because he's friends with the big boss). But the other guys...one would have actual end-user visible error messages like "the stupid polack messed up again", and had one of Shakespeare's plays in its entirety linked on one of the maintenance web sites. The other guy consistently set up SQL accounts with "password" and sysadmin privileges (I've gotten it secured now, but it's causing quite a bit of havoc for some users). Crazy and stupid, respectively. Then we have a contractor (still with us, hopefully not much longer)...who is arrogant AND stupid (with coding, anyways...quite manipulative with the non-technical people who control his paycheck). He implements concepts and technologies that he does not understand in completely useless and excessively complicated ways. He also has a big problem with turnover of his underlings, resulting in even crappier code. The rest of us want to completely scrap his project because it's so bad (the aforementioned "acid trip code"). But you know what they say: "CONTRACTING: if you aren't part of the solution, there's good money to be made in prolonging the problem."

          I am lazy: I make sure it works before it goes out, and I write it so the user can configure it to do what they need without having to bother me to do hard code changes, recompile, and redeploy. I've already got enough of that with existing code I've not yet had time to rewrite.

          So, in short, if you are neither crazy nor stupid, your code probably won't suck that bad. Every time I'm skeptical of my own code, I just look at the code I am maintaining and replacing. I simply remind myself: mine actually works. I wrote them from start to finish, so the code is consistent. My boss can look at it and understand what it's doing with his experience with older languages and teething knowledge of .NET. And the other programmers whose code does NOT suck (separate project group) have given me positive feedback on what they've seen of mine. A limited degree of self-doubt is good for keeping you honest with the quality of your work, but don't worry about it TOO much.
        • by dubl-u (51156)
          I think we agree pretty much completely on the spirit of things, and were we coding together, I'm sure we'd get along well. However, I think you got the bit about agile teams wrong.

          I've met people of the agile variety who insist that well-written code needs no documentation: that if you carve your code up into small, tight, appropriately named classes and methods it becomes obvious what your code does and your code becomes "self-documenting", [...] it's still a challenge to see the forest for the trees [...
          • Re: (Score:3, Insightful)

            by SilentBob0727 (974090)

            The reason Agile people lean away from documentation by default is that documentation is by definition redundant.

            And redundancy is a Bad Thing because? Yes, code duplication is undesirable. Clarification where it is needed is not. Structural engineers would tell you redundancy is a very, very Good Thing.

            For an agile team coding like that, I'd expect them to be doing test-driven development, working in a team room, doing pair programming, and swapping pairs every few hours.

            And scrumming twice a day? Just messing with you. You seem to be describing an XP environment... XP is known to be an unstable methodology, both in theory and practice. Heck, the flagship XP project at Daimler Chrysler floundered until the day it was decommissioned, even with the big XP cheeses at the helm. Change m

        • Re: (Score:3, Insightful)

          by Tim Browse (9263)

          Over-commented code (the kind where there's 2-3 lines of comments for every one line of code -- not every closing brace needs a reminder that we're exiting a code block, thanks!) is pretty awful too.

          That may be true, but when I think back over my programming career to date, and think about the problems I've had with code, I can assure you that "There were just too many comments!" doesn't come up all that often :-).

        • by Beardo the Bearded (321478) on Monday December 10, 2007 @03:10PM (#21645755)
          I once wrote a bit of code that was about 15 lines.

          With comments, it was about 150 lines.

          It was a reasonably tricky set of decoding code that did a lot of fancy things to get the data out of a packet for a specialized application. It worked quite well, with corruption of about 20% still being recoverable into the original data.

          Anyway, nothing about the encoder was even remotely obvious. I wanted to make damned sure that whoever had to maintain that code had at least a reasonable clue as to what was going on without having to draw out charts and wonder why the indexes used were flipping at certain points. It wasn't comments like "this is an integer." "Now the integer increases". It was more like: "If the accumulated error goes above the threshold indicated, then we have to move back at least one step to find a different pathway. Since we know that the first pathway was not a match, then we increment the error threshold, increment the index, and *decrement* the position in the message." (I can't remember exactly, it's been a year since I wrote that, I no longer work there, and there's an NDA anyway.)

          Another piece of code I wrote stripped the GPS data from a GPS module's RS-232 output. It was trivial to write the code, since it was an iterative loop. However, comments for each line made it impossible to get lost in the series of 15 nested loops and in the placement of commas and other fields. It was really handy to see at a glance exactly which lines were used to skip to any given field.

          (Special thanks to the lameness filter for not letting me post it quite right!)

          At this point, get the GPS longitude minutes:
          $GPGGA,180432.00,4027.027912,N,08704.857070, W
                                            ^^
           
          GPS.longitude_min = get_number
          GPS.longitude_min << 4
          GPS.longitude_min |= get_number
           
          Skip the period:
          $GPGGA,180432.00,4027.027912,N,08704.857070, W
                                              ^
          skip_period;
          Any coding practice has to be flexible enough to allow you to make your point. If you're not commenting because you think the code is obvious, then maybe you haven't coded real stuff, or you haven't coded really tricky stuff. Maybe I write my code with a little bit of overkill in the comments, but at least I know that years from now, anyone can take a look and know exactly what I was thinking and know how to update the code.

          My code's been reviewed by an independent auditor as "better than most".
        • Re: (Score:3, Informative)

          by famebait (450028)
          To the original poster:
          The most important part is not in your boss but in you - if you want to be proud of your code, you have to start by taking pride in the readability of you code. Your ambition should not be to write code that is readable, but textbook quality: it should be suitable not just as an example to others, but should itself be instructive to others. Not hat you can always do that, but you should hold it as something you _want_ not something you 'ought to'.

          Yes, crunch times and asshole bosses
    • by JustinKSU (517405) on Monday December 10, 2007 @09:22AM (#21640705)
      Codes is an expression of the programmer's though process. Everyone thinks in a different way. Invariably the last person's code will seem to suck because you have to think differently to understand it. Patterns were developed to create a common ground where people can think about problems in a similar way. Regardless of how pointless and off track a project might be you still should be able to design reusable concise code if you follow the right kind of patterns.
    • by Anonymous Coward on Monday December 10, 2007 @09:26AM (#21640761)
      I had this problem with a guy that was complaining that my code was full of GOTO statements, used all global variables, and didn't have any comments or subroutines. Bah, it worked so why should he bitch about it?
      • by CmdrGravy (645153) on Monday December 10, 2007 @09:44AM (#21640941) Homepage
        No wonder, that's a really old fashioned way of doing things. You need to get with the times and functional programming. Personally I do all my programming in functions, often I just need 1 or 2 big functions for a program if I make sure the functions all behave entirely differently depending on the values of the 30 or so parameters I pass to them. It's very efficient and yet still people moan !

        CalcCallWaitingTime StripIllegalCharacters CreateInterfaceToACD DrawCalendarOutline may well be quite a long title ( often it's easier to acronymise them before I hand the code over ) but it's amazing the number of loops you can reuse if you have enough switches.
        • I often find passing the function name itself as a parameter helps with loop re-use.
          That way you only need to create a single do loop and allow your cx(...) sub (result passed back in the 14th argument unless the 3rd is "E" or above in which case its pushed onto the reference you passed as arg[19 + val(arg4)].

          The last guy who tried to use the code was so awestruck with my genius he passed out!
          • by Moraelin (679338) on Monday December 10, 2007 @01:11PM (#21643915) Journal
            Ah, kids these days... so easily impressed.

            I remember one piece of code that makes even that seem tame. Assembly, mind you, back in the 386 days.

            Someone had calculated something as a 4 byte float, then took it as a 32-bit integer, swapped the higher and lower 16-bit words, wrote it into a memory location at the start of a function, and then actually jumped to that location. I.e., he actually executed that result. That was actually in the (uncommented) assembly source code, mind you, not some accidentally disasssembling a piece of the data segment and discovering that it makes no sense.

            To this day, I have no clue what that did. Awestruck is putting it mildly.
    • by Chatsubo (807023) on Monday December 10, 2007 @09:30AM (#21640803)
      A lot of the time you find that, while someone is still employed, they do a good job of hiding their mistakes and covering up. It's when they leave that things start to go downhill because now suddenly, someone has to go read and understand their code. Then you realise it's a patchwork of quick fixes and bad design, and decide nice clean rewrite is in order.

      At this point you try to justify the change to management, who will "schedule it for sometime next year", since this is not causing them any pain, only you get that priviledge. From that point on, you're stuck with someone else's bugs forever.

      Now you're upset and become very vocal about the problems you now have to deal with.

      There is a difference between "different" code that works, and bad code that routinely causes problems.

      Usually the cracks show about a week or two after the guy leaves. And by cracks, I mean serious, client affecting shit.
      • by computational super (740265) on Monday December 10, 2007 @10:18AM (#21641311)

        But your code, of course, draws gasps of admiration and awe from all who look upon it.

        Come on. When was the last time you had anything good to say about anybody else's code? Ever? All programmers say all other programmers are incompetent. And typically, management believes us.

        • Actually... (Score:5, Insightful)

          by RingDev (879105) on Monday December 10, 2007 @12:11PM (#21642859) Homepage Journal
          One of my coworkers told me the other day he loved my new authentication and credentials system I used for the Data Access Layer. So much so that he snagged it and used it in another system that had similar authentication requirements.

          Now, I've written a lot of bad code in my life, and I'd like to think a lot of good code to. I've seen beautiful code before. New attack vectors and amazing ways to approach problems I never would have though of. And each time I see those nuggets of perfection, I snag them. They get added to my pile of code samples for later use. Either in a straight copy or as a foundation of an idea that gets recoded, depending on license requirements.

          Bad code is easy enough to deal with, bad design however... that will kill a project. Bad code can be hot fixed, cleaned up, or straight up replaced. But bad design will require new work from the ground up, getting the users and management to come back to the white board, verifying the requirements... If the system is not designed to meet the needs of the users, a memory leak won't be an issue because no one will ever use the software.

          -Rick
        • Not quite true (Score:3, Insightful)

          by Moraelin (679338)

          Come on. When was the last time you had anything good to say about anybody else's code? Ever? All programmers say all other programmers are incompetent. And typically, management believes us.

          Not quite true. I can think of a few people whose code gave me no reason for complaints. To pick just two extremes out of the pool:

          - one of them is pretty much the pragmatic programmer prototype. He'll (also) apply some pattern only if it's needed, not because it would be fun to have it on the resume. Sometimes a switch

      • by Mr2cents (323101) on Monday December 10, 2007 @10:55AM (#21641747)
        I think part of the problem is that programmers lack the courage to just think. I recently had a programming problem that I thought two weeks about. That's go to work, think, write down some key ideas, pitfalls, things to do etc. on a piece of paper and go home. After these two weeks I had three A4 papers with some text scribbled on it. Then I spent one week coding, and when I finally tested it it worked from the second time (one small bug found).

        In my experience, not everybody dares to work this way. It is a bit embarrassing if your boss enters your office and you're just leaning back in your chair, day after day. But on the other hand, if they wanted someone who would always seem busy, they hired the wrong person; they should have gone for a typist. Thinking is an important part of a programmer's job.

        A second advice would be to keep abstractions as simple as possible. Think "What do I need and what API do I need to do that?". If you can get away with an API with only an init function and a "worker" function, then be my guest! K.I.S.S. is very important. Again, to make things as simple as possible requires a lot of thinking.

        And while you are thinking it helps to have enough experience to have a "mental compiler". I can write and test code in my head so to speak. But that is something you only get after many, many years of intensive programming.
    • by jacquesm (154384) <j@NOsPAm.ww.com> on Monday December 10, 2007 @09:39AM (#21640889) Homepage
      style is one eternal point of contention (except for python programmers, but they're in a straight jacket), I don't think that it is a part of 'are you proud of your code', that has little to do with what other people think of your code, but everything about what you think of your own code.

      When I look at my own code it's a mixed bag. The stuff that I earned the most money with is actually programmed quite bad, some of the most elegant stuff I wrote is sitting unused on the shelf.

      I find that in a commercial setting I'm far more inclined to 'cut & paste' to keep moving rather than refactoring just to save the time. Sure, it leads to maintenance headaches down the line and I quite often just scrap stuff and rewrite it rather than figuring out what it did and why. Tools evolve at such a tremendous clip that I don't think the lifespan of code is anywhere near the point where it could be justified to spend say an extra week or two to get an algorithm tweaked to perfection if the next release of the tool or framework is going to have it built in anyway.

      Faster machines also lead to sloppy code, I'm running a lot of production stuff on uncompiled PHP, whereas in the past I've rolled out code in assembler because I could beat the C compiler by a couple of cycles on most tight loops.

      Times are changing, and that is the biggest 'driver' against 'clean' code, it won't be long before the actual code will start to disappear. For some environments that is already happening.

      Oh well, old guys like me will find employment writing for embedded systems, which are about a decade behind the curve.

      • by Atraxen (790188) on Monday December 10, 2007 @10:00AM (#21641091)
        For the sake of the wider conversation, let me remind folks that there are still cases where (nearly) every cycle counts. One that comes to mind is is scientific computing (e.g. molecular modeling, !e.g. most analysis). So, if anyone's still missing "ye good 'ole days", there's still a need for 'Shakespearean' code...
        • by postbigbang (761081) on Monday December 10, 2007 @10:23AM (#21641383)
          I still think in cycles, or ticks.

          It comes from learning Z80/8080 assembler first, before BASIC, before C. Until that point, I knew a few macro languages.

          In my mind, I'm still in a 32K machine, living with the OS, writing strings to hardware ports, and using my own interrupt vector code in concert with the host cycles to get work done.

          When I work in C or C++ (heaven forbid #), there's a link list in my mind about array conservation, minimizing strings, using hashing and strict Booleans to get a job done.

          No, I'm not an embedded systems coder; I just end up thinking like one.

          My comments used to go thru an assembler, and I'd look at the code and try and re-optimize it. And when my code would explode, it would explode to unrecognizable shards of crap until I learned atomization (objects) and resource re-entrance. Now when my code doesn't work, my deadman's switch monitor twigs, which backstreams messages. It makes coding highly involved, but vastly more productive because *I CAN* reuse my code.

          I worry more about the OS than my own code; there's so much that's not predictable in operating systems today. They should do more work with smaller kernels and leave modularity out of the kernel. Just my 2c.
    • by noidentity (188756) on Monday December 10, 2007 @09:39AM (#21640893)

      Here are some pet peeves of mine involving dealing with other people's code. I don't think many of these are subjective either.

      • Header files you can't #include without getting errors because you didn't #include something it requires (but stupidly doesn't #include itself).
      • Lots of global variables that are read and written by several modules.
      • Header files lacking comments about what functions do.
      • Use of non-standard names for types with a fixed number of bits, instead of those from stdint.h/inttypes.h. So they have u16 or int16 instead of int16_t. Or really stupid stuff like uint instead of unsigned int (or just unsigned, which is equivalent).
      • Lack of const-correctness. Something like void print_string( char* str ); Huh, does it modify the string? No, then why does it take a pointer to non-const?
      • Unnecessary non-portability. Don't use #include unless #include isn't sufficient.
      • Internal things put in header files. If it's only used in the module, keep it in the module's source file only! Same goes for not making internal functions static, opening the possibility of clashes.
      • Files indented with two spaces instead of a tab, or even just one space. Fortunately this can be worked around with tools.
      • Unnecessarily space-taking comments about a function's visible behavior. Things with lines of stars around everything, etc.
      • Lack of structure tags, preventing forward declaration. Don't do typedef struct { ... } foo_t; do struct foo_t { }; and a typedef if necessary.
      • Macros for integral constants (yes, even in C), since enum does the job and obeys scope (yes, C has different scopes, not just C++).
      • Fundamentally, things that aren't highly modular and can be understood and used in isolation. I want to combine modules and have a minimum of complexity increase due to this combination.
      • Re: (Score:3, Insightful)

        by Nevyn (5505) *

        Files indented with two spaces instead of a tab, or even just one space. Fortunately this can be worked around with tools.

        This is at best personal opinion, and AFAIK all the actually testing done on this shows that 1 space indentation isn't enough, which is why 2, 4 or 8 spaces are the norm. My opinion is that TABs should never be used for indentation, as none of the tools will multi line things up correctly (Ie. you need to use TABs to the start of the original line, and then space to line up). Also TA

    • by sm62704 (957197) on Monday December 10, 2007 @10:13AM (#21641249) Journal
      I've seen time and time again programmers taking over for other programmers' code and saying that the previous person's code sucks. Its like a right of passage or something

      You should realise that programming is an art. In art school what you''re referring to is called a critique. It's a good thing. From an old tome I wrote about ten years ago, Steve's School of Fine Art [mcgrew.info]:

      Lesson 1: The Critique
              The ultimate in masochism. Your grade depends on the critique. In the critique, everyone in class exhibits their work, and comments on all of it. How good yours looks depends on how bad theirs looks. Each work is scrutinized and ruthlessly shredded by your competitors, whose grades depend on how good their work looks compared to yours. These people are mostly talentless losers, not unlike yourself, who desperately want their work placed somewhere where someone might see it, just like you and Vincent.

            To survive this ordeal, keep your work covered until nearly everyone has their work displayed. Place yours prominently next to the worst piece of crap in the room. While everyone is ripping each other to shreds with pompous, empty, multisyllable phrases, translate what they say into plain english, which will demonstrate to the instructor that you, unlike they, actually understand this gobbledygook. Praise everyone's work with backhanded compliments in such a way that the teacher knows that you know it's crap, while the other students think you're complimenting their work.

            Beat everyone to the punch by being merciless about your own work, especially if you've outdone yourself and have actually produced something that doesn't suck. The teacher knows what you've done right; show him/her/it that you know what you've done wrong.

            Smile smugly when you're ripped. Let your face say "HA! It worked! They HATE it!" (See Insulting an Art Student and Art History, below)

            Lastly, be an attractive woman with large breasts. The heterosexual men and the lesbians will all be trying to get in your pants and won't be hard on your work, the homosexual men will be afraid of being thought of as mysogonistic, and the heterosexual women will dismiss you completely as a total, talentless airhead. This is the only place they won't think of you as a threat.

      -mcgrew

      Condsidering the subject matter, every comment on this story should be modded "flamebait".
    • by Tom Cully (1052856) on Monday December 10, 2007 @10:54AM (#21641735)
      Q: How many developers does it take to change a lightbulb?

      A: 10. 1 to change the bulb, and 9 to say "no, I would have done it like this..."

      For me, this is part of the "Is programming is a science or an art?" argument. You can send a person to Art College and then have them paint for 10 years, and even then they won't necessarily produce masterpieces. Sometimes we comment like that on code we've taken over, because it really is awful...
    • Re: (Score:3, Insightful)

      by Brad Eleven (165911)
      My experience in inheriting others' code is that I've found the "why" to be missing. I've seen a wide range of comments, from 10K lines of C with exactly two comments ("this part is tricky" and "just in case") to a current project with 25K lines of KSH with a comment-to-code ratio approaching 3-to-1.

      I can read the code. I can figure out what it's doing. What I want to know is the reason behind, say, maintaining a counter in a file between runs in order to start over next time in the midst of a long list of
  • Same here (Score:5, Insightful)

    by polar red (215081) on Monday December 10, 2007 @09:16AM (#21640663)
    the problem is... the client doesn't always know what he wants, and the continuous changing of the specs (and hence of the code) make it a mess. It gets worse when near release some 'minor' changes have to be included and a lot of code has to be written in a very short time. There's a big difference between the theory of the 'waterfall-model'(and it's derivatives) and reality.
    • Re: (Score:3, Insightful)

      by ByOhTek (1181381)
      That, and "convincing the boss the customer isn't always right is a dumb and pointless thing for several reasons"

      1) The bos probably already knows this is some respects, however...
      1.a) Should the boss act on this knowledge, he or she will lose the customer, this is not profitable
      1.b) The company could get a bad reputation of not following the customers requests, losing more potential customers
      2) The customer, in the end, knows if the product is functional or not in their environment, better than you do. If
      • by TheSciBoy (1050166) on Monday December 10, 2007 @10:17AM (#21641281)

        In what other line of work does principal construction begin before the customer has defined what it is they are ordering?

        A software is not a product in itself. It's not like an "apple" or an "orange", it's more like a "building" or a "vehicle". A building and a vehicle can be the solution to many different problems. A truck doesn't necessarily solve a customers problem if he's looking for a way to transport people in style from A to B.

        But while I think that most people understand this, they have a very fuzzy and indistinct concept of the cost of changing the specification once construction has begun because you can't walk the customer out to the building, point at the construction and say: "To make the changes you require we will have to tear out that wall there, remove all the concrete laid here, that will require a week and scrap more than four tonnes of construction material".

        This is where software engineering comes in: With a good model and by sticking to the principle that you begin with a specification from which you construct a series of test to see if the specification has been fulfilled. From the specification a design is made. The design specification is used to implement tests to see that the design has been followed. From the design the code is written and on the code the tests are run.

        Now when the customer changes the specification you can look at the design and the code and see (hopefully) how substantial the changes will be and what the cost will be. Your customer will thank you for being more accurate in your estimation, for pointing out the costs (which is the only thing your customer will care about, remember that time is money and is just another type of cost).

        I have so far only worked in one workplace where this model was used and it was used very successfully in my opinion. Writing all those documents surely sucked, until it came time for implementation, which was frighteningly quick and painless. The ultimate pride for the well documented, well planned, well concieved and tested code has made me utterly incapable of being satisfied with any other way of working (which is why I've switched jobs a lot).

        Changing to a structured approach to working is costly, but the benifits are bountiful and will ultimately save money and time. I can almost promise that while you might lose a customer or some goodwill of a few customers in the interim, in the long run, the customers will flock to you since you are delivering on time, the functionality they asked for.

      • by sjames (1099)

        There are two good ways to defend against shifting requirements.

        First, keep in mind during design that changes will happen. They may be in 5 years or they may happen before the first line of code is written. If your design is modular and consistantly uses a decent internal API, many changes won't require a great deal of pain.

        The second defense is the "change order". If you do not have a change order process in place, the customer will expect to make major revisions at the last minute without consequence

  • If so, then what is holding you back from realizing your full potential?

    This post [slashdot.org] should explain it. If you think hiring practices are discriminatory for minorities, try being like me!

    Cherish YOUR THUMBS!
  • Getting better. (Score:5, Informative)

    by Ihlosi (895663) on Monday December 10, 2007 @09:20AM (#21640693)
    It is buggy, slow, fragile, and a nightmare to maintain.



    When looking back at my first project, I feel the same. But I also think that I've learned a lot from it, and all subsequent projects were much, much better.


    So, by being "not proud" of your code, you've made the first step towards improving it.

    • Re:Getting better. (Score:4, Informative)

      by RandoX (828285) on Monday December 10, 2007 @09:34AM (#21640837)
      If you start coding from the beginning with the best possible methods, then congratulations. If you're like myself, and most of the rest of us, you're learning better ways to do things as you go. I know that I can't help but look back at older projects and think that there are better ways to do what I've done. Now I know better. Now I'll write things in a more efficient and maintainable way. I can only hope that in a few years I'll look back at the code I write this week and have an even better, cleaner, faster, and more maintainable way to do it.
  • More Design (Score:3, Informative)

    by Loophole64 (871990) on Monday December 10, 2007 @09:22AM (#21640709)
    Often times you can avoid a lot of this headache by spending more time in design. If you can flush the project out in some detail during design, and include the customer, more of those changes will be included in the original design before you ever start to code. Unfortunately, others in your organization will often feel like design time is wasted time. You have to be steadfast in your will to spend time in the design phase.
    • Re: (Score:3, Insightful)

      by 0xdeadbeef (28836)
      Design time is wasted time. People don't know what they want, and they won't make meaningful decisions until they have something running in their hands.
    • Re: (Score:3, Interesting)

      by Oligonicella (659917)
      No kidding! For Christ's sake, where have these sloppy writers been for the last forty years? It's not like quality coding techniques are anything new. Client interviews with textual/graphic feedback and an ongoing demonstration combined with clean code written for the next person who will look at it; been doing that since the afore mentioned Apple times as well.

      The continuous feedback of easily understood information as to what the design is and where you are goes a long way to keep the client from b
    • Re:More Design (Score:4, Insightful)

      by Foolicious (895952) on Monday December 10, 2007 @10:25AM (#21641395)

      Often times you can avoid a lot of this headache by spending more time in design.

      Theoretically speaking, yes. Practically speaking, no. In fact, no no no no no no no. I've found that more time in the design phase means less time in the actually-doing-stuff and fighting-about-scope-creep and why-have-we-only-1-day-for-testing-and-bug-fixes? and you-didn't-ask-for-that-yes-I-did-no-you-didn't-yes-I-did-then-show-me-where-it-is-in-the-requirements phases.

      You're 100% right that better design usually allows for better code; however, when you're in the real world where your actual work is interrupted every 2 or 3 hours by "status" meetings or calls from a "project manager" or some kind of "business analyst" or whatever asking if something is done, and your clients only care about it working just then and there so they can meet THEIR client's deadline (so they can then meet THEIR clients' deadlines and so and so forth), well, then you just get the project done, knowing full well that your questionable code is screwing yourself or someone like you over in the future.

      You really have no choice. Principles, aside from the deeply held moral ones, don't carry much weight, especially if you work at a larger company. Calling for standards is all good and well -- until my fat, white (sometimes pimply) butt is on the line. Then I just get it done. I'd rather I get another paycheck than piss clients off and have 10 meetings (cutting into even more of my time) talking about how to implement coding standards that will, for all intents and purposes, never actually be implemented, even after we've decided to implement them!

  • by MosesJones (55544) on Monday December 10, 2007 @09:22AM (#21640711) Homepage

    Getting good IT practices is about establishing a business professionalism in IT that is respected. This means that you have to explain to the business what "good" looks like, you have to understand the business drivers so you can put your challenges into that context and you have to talk to the business in terms it understands.

    All too often IT folks bitch and moan about coding, testing, requirements, design time or whatever and how its all the fault of the business. This is victim mentality IT, the way to change it is to actually work out what "good" would be for the business and then work with them to deliver it.

    This means the most important coding skill in successful IT departments is the ability to communicate.
  • The customer is not always right.

    Otherwise, it would be the other way around, and THEY would be serving YOU.

    AS you might guess, I hated retail.
  • by Max Romantschuk (132276) <max@romantschuk.fi> on Monday December 10, 2007 @09:27AM (#21640771) Homepage
    I seem to find that trying to code more slowly than I could helps a lot. I'm not the most efficient coder there is, but I tend to produce less bugs and have more time to make better design decisions when I slow myself down.

    I've had several jobs where I've found that although management never seems to approve of a slower process in itself, they do begin to see the values once they notice that my code tends to be less buggy than that of my peer programmers.

    As for turning around bad practices... That's always hard. Culture is a tricky thing. But it helps to use analogies, lots of analogies! System grown too large with too many kludges? Compare to building a skyscraper on the foundations of a cottage. Management wants to speed up a project by senselessly adding more people? Compare to: "One woman can make one baby in nine months. Two women can make two babies in nine months, but two women can't make one baby in four and a half months..."

    Be creative, be thorough, and be proud of your work. Always try to make the next iteration better, but also remember that sometime meeting the deadline is all that counts.

    My two cents, I guess...
  • Apples/Oranges (Score:4, Insightful)

    by ilovegeorgebush (923173) on Monday December 10, 2007 @09:27AM (#21640773) Homepage
    In programming, there are a million and one ways to do the same thing. There is no right or wrong, only good & bad. I've seen some damn shocking code over the past few years, and I've written my fair share too. It's swings and roundabouts, it's up to you to learn from your mistakes and push yourself as a programmer to better your code quality. Keep in mind that what you right is what people use, and it's the difference between "computers suck" and "hey, that was cool!".

    And as the first reply said, someone will always criticise your code. Decent programmers know this and still do their best.
  • by Rik Sweeney (471717) on Monday December 10, 2007 @09:28AM (#21640777) Homepage
    No matter what I think of my code, I always know (pray) that it'll never be bad enough to be submitted to Worse Than Failure [thedailywtf.com].

    That said, I do revisit code that I'd written a few years back and think "WTF were you thinking?!"
  • At my last job, the standard response to any request was "Sure, we'll do that, when do you need it?" and it "HAD" to be done whenever the arbitrary date given was. There was no reasonable estimations of time or scheduling given. The desired end product was a moving target, changing daily. Sadly, the department that was most frequently shorted on time was QA. It took as long as it took to write, and when we handed our best (rushed) efforts to QA there simply wasn't enough time for any regression testing
  • I'd say that you should always be proud of your code and always do your best writing it. I don't mean that your code must be perfect -- nobody is perfect, but if under current time constraints, requirements and all other circumstances you can do better, then do it.

    When evaluating your old code you should take circumstances into account to: may be you were in a hurry and "fast" was more important than "good" at the moment -- it's OK, it's a part of a job. Go back and refactor later. Besides, you are ma

  • Management (Score:3, Informative)

    by Algorithmnast (1105517) on Monday December 10, 2007 @09:30AM (#21640801)

    I know that with my own management, they're quite uninterested in quality - and entirely interested in the "schedule". They have a schedule, and want to meet it with our client (we're consultants) no matter what that does to our quality.

    Of course, once the code is accepted by the client then by #definition it is good enough and changes to existing code are only possible if we can prove that the existing code is buggy.

    Then there's the bizarre requirement that developers use copy/paste whenever possible. It's not as if we get paid by the line, but it seems that some of the senior architect types think that LOC matters. (no jokes please)

    Add in management's desire to see as little change to things as possible, we get a very poor heurestic for Hill Climbing [wikipedia.org] as a model of our software development "practices".

  • by PIPBoy3000 (619296) on Monday December 10, 2007 @09:30AM (#21640805)
    I have a lot of applications that are elegant enough. It may not have perfect validation for every field and not all the GUI bells and whistles, but it does what it's supposed to. I know my share of developers that spend a ton of time making their code elegant and beautiful. In one case, the developer spent so much time making their N-tier application with huge numbers of tables that were normalized to the bajillionth degree that they were finally let go. The goal is to meet the need, not to fulfill some inner desire to create art with lines of code.
    • Re: (Score:3, Insightful)

      by oliderid (710055)
      Personnally an elegant code is:

      - readable (meaningful variable names & tabulation)
      - commented
      - pragmatic (using enum, and all)
      - basic design (classes and methods should have been designed prior to any coding (at least the biggest par of it). You feel it when you read a code.

      For the rest...If a method needs 20 lines or 100...As long as I can understand it, I don't care.

  • TIME! (Score:4, Interesting)

    by microTodd (240390) on Monday December 10, 2007 @09:33AM (#21640827) Homepage Journal
    The answer to your question as to what is holding you back is complicated and multi-faceted. I'm sure you'll receive many interesting answers (and I look forward to reading them...hopefully it'll help me become a better coder).

    From a pure Computer Sciency standpoint, remember that no code is ever completely bug-free...its mathematically impossible. Testing does not prove the absence of bugs, it only proves the presence of successful use/test cases.

    But the number one thing holing me back is time. When I'm coding on the company's dollar, there's only so much time to spend in design, in writing test cases, in having someone peer review your code. And thus, there's just not enough time to spend doing things in the absolute, 100% correct way. There has to be some compromise.

    I suspect that even if I had time, I would run out of mental energy first.
  • Lost out (Score:5, Funny)

    by gaou (1200987) on Monday December 10, 2007 @09:33AM (#21640829)
    "It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration."
    Edsger Dijkstra


    Sorry mate, there is no hope :)

  • ...their company to stop or cut back on 'cowboy coding' and adopt best practices?"

    I didn't need to, I work for a competent company that aren't going to compromise the quality of their product on the whims of a single customer.

    I also happen to think my code's great, thankyou very much. I couldn't imagine going through life thinking my code was awful. I'd lose the will to live and find another career.
  • by Hektor_Troy (262592) on Monday December 10, 2007 @09:38AM (#21640877)
    The best code I've ever had the pleasure of working on, was made when I worked for an actual engineering company. Not software engineering, but engineers that build physical stuff.

    They understand the need for excelent documentation, rock solid requirements and that you don't get halfway in a project and change its direction (ie, "sure, the Golden Gate is halfway done, but we'd actually like it to go from Lime Point and meet up with the Bay Bridge around Treasure Island Road"). They understand that some things take half the time to do but are four times as expensive to maintain, and they prefer quality over quantity.

    Least the ones I worked with
  • Eric Raymond wrote, in "The Art of Unix Programming": "The combination of threads, remote-procedure-call interfaces, and heavyweight object-oriented design is especially dangerous... if you are ever invited onto a project that is supposed to feature all three, fleeing in terror might well be an appropriate reaction."

    The product I work on at work features all three. It can be 'interesting' to maintain sometimes. That being said, it's frequently possible to rewrite sections and management sometimes listens to the programmer types and has let us restructure things sometimes. For example, we've mostly gotten rid of the RPC stuff.

    When I want to satisfy my urge to work on good, clean code, I do some open-source work. Open-source tends to have that, because nothing else tends to work for very long.

  • All Code Sucks... (Score:3, Interesting)

    by iBod (534920) on Monday December 10, 2007 @09:40AM (#21640905)
    ...to somebody, for some reason.

    There is no Holy Grail of code.

    What is good coding style to me, may be anathema to you.

    Ok, there is utterly shit code (which probably accounts for a fair proportion of all code if my life experience is anything to go by), then there is 'run of the mill' code, then sometimes rare glimpses of 'great' code.

    Great code for me is when you see it and understand the programmers intention, and you think: a) I would have done it that way, or more likely b) if I was smarter I would have done it that way. You learn from great code, if you're already a good coder.

    I think the greatest obstacle to 'great' code is 'language fascism'. Some languages are better than others, that's true, but they way some people carry on you'd think it was only possible to write 'great' code in their language of choice. This behavior is generally exhibited by those that can code in one (or at most two) languages only.

    I'm generally proud of my code and am happy for others to scrutinize it. All that means is that I spent the time to make it as good as I could withing the prevailing time/cost constraints.

    I used to write a lot of assembler. Some of my colleagues used to think it was cool to use obscure instructions, in unintended ways, just to show how 'cool' they were at flipping the registers. I never subscribed to this idea and always used 2 or 3 common instructions instead of one 'neat' instruction. Performance never seemed to suffer and maintenance programmers were eternally grateful.

  • by Dystopian Rebel (714995) * on Monday December 10, 2007 @09:41AM (#21640915) Journal
    After a long time in the software industry, I came to realize that Code Is Communication.

    By far the largest part of the lifespan of any code is Maintenance. Code has to be intelligible. Not just through commenting, but in every construct and usage.

    Think about effective communication. The effort to be clear will improve what you are doing. It will also make your mistakes evident so you can correct them.
  • by eebra82 (907996) on Monday December 10, 2007 @09:43AM (#21640929) Homepage
    Gather around me kids, for I am sitting here in my 18th century rocker to tell you a story about a programmer.. A good programmer..

    I used to work for a small-sized IT business; a popular community that housed some 130,000 members. It began with the loss of a fellow employee who had basically coded 99% of everything on the site. To that date, everything had worked fine. We had some issues every now and then, but a backup system helped us from getting hammered if anything bad happened.

    We never worried too much about him leaving because, for starters, I had some experience with the code/system. In addition, the now departed programmer had left a comprehensive list of features and explanations of his system that would help any programmer (that would replace him) to get around any tricky problems that would/could occur.

    Unfortunately, I won't go into what type of business this was, but let's just say that it's not typical programming skills. When I began looking for his replacement, I realized how hard it was to get someone with adequate skills and all the knowhow that was required besides the actual programming. As we were on a tight budget, it was important for us to find that one guy who didn't expect a zillion dollar salary. Typically, that would be someone who shares our interests, a recent graduate who knows his ways around programming.

    Eventually I found one guy who claimed to be all that we wanted. After a month, it turned out that the guy was more and more frustrated over how things worked at the company. He disliked about everything about the code and spent most of the time cursing. At this point, I started to believe that our entire code sucked.

    Roughly a month later, we decided to rebuild "everything" so that he could have his ways around the code. Since we only had one programmer, I had to comply because it was an important role in the company. My limited coding skills provided no extra help in evaluating our current code, so I trusted this guy since he seemed to be very thorough and experienced. Also, I was promised it would take no longer than one month to do all this.

    What a fool I was. If it ain't broken, don't fix it. I should have known, but a company on a tight budget and no one else with good programming skills forced us into this move. Turns out, our super experienced programmer needed not one month, but two, three, four, five, six and seven months to complete his task. By then, he had reprogrammed almost everything and merged some of it with the old code. We waited for the relaunch of our software with great anticipation. Three! Two! One! Go! Oh crap, everything f*cked up.

    Following the launch of our new software, we had months and months of trial and error problems. Members were complaining and nothing went in the right direction. Eventually, we were essentially bankrupt and had to let the superb programmer go. The guy who had left us with a huge mess.

    When I read this Slashdot story, I had a smile on my face because I learned that a programmer can only know that his code is perfect by the response of many other programmers who can view his code (i.e. open source). Some programmers seem to think their code is perfect and that occurring bugs are caused by impossible-to-foresee problems. The point of my story is that if you truly want to know if you are a good programmer, you must let a lot of programmers decide that for you. Unless your name starts with J and ends with ohn Carmack, of course.
    • by petes_PoV (912422) on Monday December 10, 2007 @10:22AM (#21641371)
      .. is to criticise the code they inherit.

      All this means is they have a fixed idea of how it should be done and cannot bear to see it done any other way. Frequently (as you found to your cost) the final product is the result of trial-and-error techniques. It's very likely the original programmer thought of and tried the way it should be done, then found the flaws in this approach and adopted methods that produced the results.

      It's equally likely that some of the ugly code in any implementation is to get around bugs in the development system, programs it interfaces with or even the O.S. itself. The inexperienced programmer only sees the ugliness of the end result, they assume that the original programmer was dumb/lazy/old-fashioned (because that's what they see in themselves?) and in their arrogance assume that there's nothing worth keeping and only a complete re-write will meet their high standards. If only this was Usually none of the "experience" is documented - only a description of what a module does, not why that method was chosen.

      Of course the BIG mistake is to only have one programmer. What happens when they take a break or leave? Everything stops.

      • All programmers criticize the code they inherit. The key point is what the criticisms are. As a rule of thumb:

        * Low-level form and factor: The code is written by somebody of much lower ability, so the code is disorganized with lots of run-on functions. You can understand the code, but modifying or maintaining it is next to impossible just as speaking with invalid grammar is very difficult if you know better (ie "somebody sent up us the bomb", or repeating verbatim pretty much anything GWB says).
        * Syntax
  • TCO (Score:3, Informative)

    by devnullkac (223246) on Monday December 10, 2007 @09:45AM (#21640949) Homepage

    Saying "no" to the customer is not normally what's called for. Instead, your team must clearly state the total cost of any proposed change. Factoring maintainable quality into cost estimates is an art that an organization must learn if it wants to get asked to do another job after the money for this one runs out (project drift leads to no results leads to unhappy customers, as you well know). When the customer responds with "Well, isn't just as simple as changing X into Y?" then that's when you get to say "no."

  • Yes (Score:5, Funny)

    by Average_Joe_Sixpack (534373) on Monday December 10, 2007 @09:56AM (#21641065)
    I often use "Programmer: Alan Smithee" in the comment header
  • Yes, yes and yes (Score:4, Insightful)

    by YeeHaW_Jelte (451855) on Monday December 10, 2007 @09:56AM (#21641067) Homepage
    Yes, I am proud of my code, or maybe not always the code but at least my coding. It's not always possible to create beautiful, well mantainable code. I try to, but sometimes there's just not the time.

    Yes, I have convinced my employer to stop allowing cowboy coding practices -- she didn't even realize it was happening. I'm currently head of the programming division of a inhouse IT dept for a large travelagency specialized in cruises ... it's a pretty large department for such a small company, as we write all our inhouse software ourselves and have been for the last 5 years. When I came to work here, the codebase was about that old -- 5 years -- and maybe a two dozen different 'cowboys' had been writing the software resulting in a large heap of steaming shit. They were not centrally coordinated and everyone of them was doing things in his own style either out of laziness of ignorance.

    Anyhow, I managed to convince the CEO that there was a problem ... she had no idea that it was a mess, the company being a travel agency and she having very little knowledge of automation herself. I used a difficult coding project (connecting to a GDS, the guys that administer plane reservations, car rental, cruises etc) and a general optimation project ( the application was becoming very slow due to all the bad programming going on ) to build her confidence in me and asked her to put me in charge of code sanity. She did.

    I am now trying to reform the bunch of code cowboys that currently works here to a well disciplined programming team ... and I hope I'm succeeding. Gave them code standards to work to, asked them to clean up the code base where they stumbled upon crappy pieces, moved from Visual Source Safe to Subverion (thank god!) and started regular meetings once a week.

    The codebase is still very messy at places, but many basics (use of one and only one database class e.g.) have improved very much and I think the people here are happier for it. It's much less frustrating to work on nicely formatted code that doesn't have braindead sections that aren't commented.

    To make a long story short, if you're not proud of the code you write, make sure you improve it.
  • by w4rl5ck (531459) on Monday December 10, 2007 @09:59AM (#21641083) Homepage
    I came to the conclusion that you are the only person who is ultimately responsible for the state of the code you write is YOU. Nothing else, no one else.

    Project deadlines, crazy customers, chief engineers, thunderstorms, even a Tsumani. It's just you.

    Reason:

    if you write buggy code, whatever the reason may be, it falls back to you. You will have to fix it, you will be MADE responsible for it. EVERY time. No one asks WHY you did it.

    And you don't like it yourself, which is a bad thing. One should LOVE his work, not hate it.

    If you force yourself to push everything else into a state that enables YOU to write good/nice/beautiful code, you will gain something. If not, you will suffer. That's about it. It has nothing to do with other people, with companies, with unemployment.

    So, get up, and write that good code. Whatever it takes.

    Good luck :)
  • by Opportunist (166417) on Monday December 10, 2007 @10:11AM (#21641227)
    Generally, whenever I complete a set of code, it's perfect. It's flawless. It's the stunning pinnacle of coding, and it should go on some kind of display page where everyone can marvel at it, worship it and experience its perfection so they may find true enlightenment.

    Usually, when I unearth the code 6 months later I wonder if there's any way to get this horrible piece of hacked crap out of the CVS somehow...

    It's just that, well, you learn. You improve. Yes, even after more than a decade of coding, you still learn and improve. You learn new tricks, you learn to use new libraries, and you discover better and more efficient ways to use them by using them. So generally, yes, I'm proud of my code. For a while.
  • To be honest? (Score:3, Informative)

    by stonecypher (118140) <(stonecypher) (at) (gmail.com)> on Monday December 10, 2007 @10:16AM (#21641277) Homepage Journal

    I am downright embarrassed by the quality of my code. It is buggy, slow, fragile, and a nightmare to maintain. Do you feel the same way?
    No.
  • by Caine (784) * on Monday December 10, 2007 @10:49AM (#21641663)
    Ok, so this might sound a little harsh, but you see, the solution to your problem is this: code better. It really is that simple. Yes, it's nice if you can anchor things with project managers or whatever you have above you, but it's not really necessary.

    Having problems with bad interface? Design better interfaces. Jumbled, complex code? Refactor it. Slow execution? Improve the algorithms. There's basically no project that takes longer time by doing things right, more often than not the opposite is true. A good refactor can save tons of time.

    There's no magic bullet, however much support you get from superiors or coworkers. The only thing you can do is simply write better code.
  • by ebbe11 (121118) on Monday December 10, 2007 @10:49AM (#21641669)
    ...as if the guy who is going to maintain it is a 6'6" tall two feet wide bodybuilding psychopath who knows where you live.
  • by martyb (196687) on Monday December 10, 2007 @11:55AM (#21642635)

    Many good comments already. I'd like to add some based on my experiences since 1972.

    Background: I was fortunate to be introduced to structured programming early on. I've used, and helped develop/test tools to implement, various coding methodologies (CASE, anyone?) I've worked on operating systems and compilers. Yes, plural on each of those. I've worked at huge multi-nationals and a 3-man startup.

    Observations:

    • I've written crap code. I think it's part of the rite of passage. I did the best I could with what I knew, and when I knew better, I tried to do better.
    • I've read books and taken courses, but there's no comparison to just diving in and reading LOTS of OTHER PEOPLE's code... and then learning from it.
    • Attitude is important. There is a HUGE difference between "That's stupid" and "Why did they do THAT?" Be open to be educated.
    • Be organized. In your thinking, notes, and code. In my experience, bugs tend to congregate at the interfaces. Be it a procedure call or return or in an interrupt handler, I try to keep things as clean as possible. Hacks WILL come back and bite me/others.
    • Make junk stick out. When I'm pressed for time and know I'm taking a shortcut, I flag it as such. It's easier for me to find a needle in a haystack if I use BIG needles.

    Lastly, here is a quotation I found back in the 80's (IIRC from someone at SofTech) and it has guided my thinking ever since:
    Strive to understand your problem.
    Don't try to solve it.
    A fully-stated problem
    embodies its solution.

  • by inKubus (199753) on Monday December 10, 2007 @12:11PM (#21642855) Homepage Journal
    Adopt a development methodology that defines what features will be developed and what features WILL NOT be developed. Now you have a place to put all those "great ideas" people have while you're still making the base product. You can also keep them in mind while making other modules, so you know you can make them later. This eliminates scope creep. It may not seem like a piece of paper will work, but as a society we all know the power of forms. Act like it's not your choice, that someone in management is making you use the methodology. No one will want to contradict anyone else so they will just accept it. And when it works, and you come in on-time and on-budget it will become part of the corporate culture.

    Your deliverables (above) will be a part of your project charter. You will also include stuff like: a list of stakeholders, RISKS AND ASSUMPTIONS (such as a deadline not being met, etc.), testing, and of course "Success", which will be a list of metrics that define a successful product (ie: it can generate payroll checks, it can print report A, etc). Then, take your project charter (look it up on google) and put a bunch of lines on the bottom for you, the team and the management and the key users to sign off on. Do not start work until it gets signed off. Then make a copy for yourself and file the original with the project documentation. Work and complete all the features to be developed. At the end, take the project charter and make sure everything is fulfilled, then give it to the "customer" and have them sign off again for completion (after you demo the software).

    Usually scope creep means poor project management, and as a developer you can't expect anyone else to do it. Just do it, you will be very thankful you did. Also, if it's a short project, try something called Quick-Kill [ddj.com] project management. Large projects need a better methodology. I use one I made up that's based on the quick kill and some microsoft stuff, with some unix version control stuff, and oracle business process analysis stuff... Over time you will develop your own methodology and become a star senior programmer making $300,000 a year.

    Have fun
  • Occasionally I ... (Score:4, Interesting)

    by kcdoodle (754976) on Monday December 10, 2007 @12:26PM (#21643135)
    Once in a while I take a small change and tell the client/boss/myself that it is a really BIG change.

    Then I go through a totally re-write the code from end-to-end. I look for unused sections, variables, etc. I re-order all the logic so that it is logical. Then I test for the necessary period of time.

    Since most of the code is already written, I start by writing out the business rules and I make the order of the code follow the order of the business rules, more-or-less. I put ALL of the business rules into the code as comments. I also send the rules to the client/boss/myself/others.

    Doing this just once a year, on each critical section of code actually saves me much more time than the initial investment, so everyone wins.
  • legacy (Score:4, Interesting)

    by suitti (447395) on Monday December 10, 2007 @12:41PM (#21643435) Homepage
    My last two projects have been to babysit and sun down legacy systems. These were written in Perl, are web & database based, were written over a period of about ten years by multiple people, had no development system (all changes are made in production), and are each at least a half million lines of code.

    One such system has two very different kinds of programmers. One kind produces very small, tight, elegant code. Each line may be complex, but there aren't very many of them. Another kind generally codes for conceptually easier tasks, and has a verbose style. Individual lines are trivial assignments, but there are sometimes thousands of them.

    The elegant code is MUCH more difficult to debug. It's also, generally, broken much less often. The verbose code is generally very easy to fix.

    But i've gotten an appreciation for other ways to do things. And, there aren't nearly as many of us 'elegant coders' out there for replacement. But i still don't see how some apps can be accomplished at all without us. This appears to be language, library and tool independent. Fred Brooks seems to have something to say about this.

    I'm firmly in the realm of 'elegant coder' myself. My favorite piece of late is 750 lines of very dense code involving a seven dimensional hash (but sometimes six - it varies) with dynamic indexes. It replaces a 25,000 line chunk that had to be changed every year. The new bit never needs change. However, despite ample documentation and three tutorials, i was unsuccessful in showing the new team how it worked. The new system has designed this bit out completely.

    One thing about both projects is that the employer either started a project to replace them, or actually replaced them. In both cases, it was an incredible amount of work and expense to do this. Millions of dollars. It would have been both cheaper and better to fix their problems, and update their user interfaces. At least, once an appropriate programmer was found. Oddly, we have at least two on our current team.

    Oh, yes. The replacement projects went over budget and were late by at least a factor of two. Much more, if you consider that something like half of the functionality was removed. And there seems to be one chunk that the new team doesn't seem to be able to deliver. Perhaps the new team needs an elegant coder.
  • In 2 letters... (Score:3, Informative)

    by worldcitizen (130185) on Monday December 10, 2007 @03:16PM (#21645855)
    >I am downright embarrassed by the quality of my code. It is buggy, slow, fragile, and a nightmare to maintain. Do you feel the same way?

    No.

    Honestly, most of the time writing bad code is not faster than writing reasonably good code.

    To improve even more, try having a policy of doing a quick code review before non trivial check-ins. Knowing that you'll have to show and explain your code to a peer, that does help in resisting the temptation to take some shortcuts (e.g., why save time writing when it will take longer to explain). Code reviews should be easy to "sell" to upper managers, as they provide a certain degree of mitigation for the risk of one programmer leaving.
  • Customer = Wrong (Score:3, Interesting)

    by 7Prime (871679) on Monday December 10, 2007 @08:12PM (#21649819) Homepage Journal
    The unfortunate truth, and this goes for ever profession, is that the customer is almost NEVER right, in fact, you can count on them being wrong about 95% of the time.

    The worst part is when the customer doesn't know what's best FOR THEM. Especially when it's your job to do what's best for them... then you have a contradiction. I work in advertising, and I run into this constantly. It's my job to help my clients sell their products/services, and they've hired me to do just that. But many times, clients think they know how to do it themselves, and then tell me what to do, when their ideas could, likely, harm their image and their sales.

    What do I do? They've hired me to do my job and help them, but their very instructions will certainly harm them. My hands are tied, I just want to scream at them, "Let me do my job, and make you lots of money!"

One man's constant is another man's variable. -- A.J. Perlis

Working...