Slashdot Mirror


Are You Proud of Your Code?

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

110 of 682 comments (clear)

  1. Something to note about other people's opinions by suso · · Score: 5, Insightful

    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.

    1. Re:Something to note about other people's opinions by DeeQ · · Score: 2

      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.
    2. Re:Something to note about other people's opinions by JustinKSU · · Score: 5, Insightful

      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.

    3. Re:Something to note about other people's opinions by Anonymous Coward · · Score: 5, Funny

      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?

    4. Re:Something to note about other people's opinions by Chatsubo · · Score: 5, Insightful

      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.

      --
      > no, yes, maybe (tagging beta)
    5. Re:Something to note about other people's opinions by jacquesm · · Score: 4, Interesting

      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.

    6. Re:Something to note about other people's opinions by noidentity · · Score: 5, Interesting

      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.
    7. Re:Something to note about other people's opinions by CmdrGravy · · Score: 5, Funny

      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.

    8. Re:Something to note about other people's opinions by LiquidCoooled · · Score: 5, Funny

      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!

      --
      liqbase :: faster than paper
    9. Re:Something to note about other people's opinions by Atraxen · · Score: 4, Informative

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

      --
      Be careful of your thoughts; they could become words at any minute...
    10. Re:Something to note about other people's opinions by sm62704 · · Score: 4, Funny
      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:

      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".
      --
      mcgrew's razor: Never attribute to stupidity that which can be explained by greedy self-interest
    11. Re:Something to note about other people's opinions by computational+super · · Score: 5, Insightful

      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.

      --
      Proud neuron in the Slashdot hivemind since 2002.
    12. Re:Something to note about other people's opinions by postbigbang · · Score: 3, Interesting

      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.

      --
      ---- Teach Peace. It's Cheaper Than War.
    13. Re:Something to note about other people's opinions by SavedLinuXgeeK · · Score: 2, Insightful

      Thats nice if you are an artist, but most people's code is paid for by XYZ company. Many of these companies have coding standards, most languages used have coding standards, and there are so many proven and accepted design patterns. This is to say that personal flair to coding style is fine, but if you are avoiding conventions, defying standard design patterns, and doing whatever the heck you want, then that is unacceptable.

      I know its stated that design patterns should be followed in the parent's post, but that coupled with standard conventions should keep other people's code form 'sucking' because you shouldn't have to think differently to understand it.

      --my $.02

      --
      je suis parce que j'aime
    14. Re:Something to note about other people's opinions by goatbits · · Score: 2, Insightful

      It has to do with ego. Most programmers have this huge ego thinking that they are the smartest programmer around. It is rare to find a programmer that believes there code could be improved. They also believe that there way is the best way.

      A solution to this is to apply simple checks to the code.
      1. Does it function?
      2. Is it readable?
      3. Does it obey functional rules. IE (It does NOT over write memory or what not).

      It the code passes these simple rules the code is fine, leave it alone, it does NOT suck.

      This does not mean it could not be improved in some way. Open discussions in code reviews could enlighten every one. (Please leave your ego at the door).

    15. Re:Something to note about other people's opinions by Tesen · · Score: 2, Insightful

      One has to ask also, is it the code that breaks or is it the underlaying system the code is written around? I left my last job in a hurry (was about to kill my boss... seriously, that bi-polar bitch just generally pissed me the hell off to the point I was about ready to come in with a tactical nuke... no really kaboom ya bitch!).

      Anyhoo, the systems I was tying together were old mainframe systems with SAP and then my own SQL backend. So you'd get data that you had to match between legacy and SAP, then of course the code would not "break" but you'd need to add some logic to massage the data. Of course, I left and suddenly the data issues were caused because I could not code, it had nothing to do with an ever changing difference between a legacy system built 25 years ago and an SAP implementation that still does not work right.

      My basic response to one critic I saw after I left was: "How come they got the data when I was there and now they can't get it because I am not?" Those that can do, do... those that can't just bitch and moan.

      I got stuck supporting a very old delphi application in another job, it pulled in flat files from another system daily, often these files would not show up due to batch jobs failing. I had MQSeries setup to pull in the same legacy data this app needed for some other systems. The first thing I did was to populate the delphi application (I was not given the time to convert it to a full SQL backend/rewrite it :P) paradox tables from a SQL DTS package. My team members said the previous coder "sucked" because of the flatfile populating, they were in error - he did not suck! That mechanism for data updates was the ONLY method available to him in 1997. People judge way to quickly, I think it is a matter of ego stroking to make them feel better about themselves.

      Tes

    16. Re:Something to note about other people's opinions by nickyj · · Score: 2, Interesting

      I beg to differ. Most of my work is in Perl and I work with one other person. Most times we are working on our own programs which work together eventually. We have different coding styles (helps us know who wrote what) and we often have to look at and adjust each others code. We usually bust on each other for mistakes and laugh at some of the comments we put in. Glad clients never see our code :)

      --
      Causing Chaos Everywhere,
      Nik J.
      The strange world of a loner, in a populous city, drowning in society
    17. Re:Something to note about other people's opinions by Tom+Cully · · Score: 4, Funny

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

    18. Re:Something to note about other people's opinions by Mr2cents · · Score: 5, Insightful

      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.

      --
      "It's too bad that stupidity isn't painful." - Anton LaVey
    19. Re:Something to note about other people's opinions by gardyloo · · Score: 2, Funny

      It the code passes these simple rules the code is fine, leave it alone, it does NOT suck. That's because it puts the lotion on the skin, or it gets the hose again.
    20. Re:Something to note about other people's opinions by SilentBob0727 · · Score: 5, Insightful

      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.

      --
      Life would be easier if I had the source code.
    21. Re:Something to note about other people's opinions by mwvdlee · · Score: 2, Funny

      So what I'm asking is: why have I always heard that #including in your headers is a big no-no?

      Everybody does it, from companies big to hobbyists small, so therefore a university cannot possibly allow it.
      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    22. Re:Something to note about other people's opinions by cayenne8 · · Score: 2, Interesting
      Wow...do people out there really have TIME for coding methodologies, reviews and the like? Most of the time I've done it...is get it out of the door yesterday, and make it work however you have to.

      I started looking up the terms being thrown around here lately for coding...'agile', 'cowboy', etc. I'd never really heard the terms much.

      Do places really have all this stuff laid out for programmers? Standards? Naming conventions, development cycles? How do they find the time for that? I've never really seen timelines that allowed for that much time and long deadlines before.

      I've heard the theories, but, have never really seen them in practice. How many out there do all of this...or just part of it, or moreso, pay it lipservice, and jump in there and write as you have to to get it working and out the door to meet a deadline?

      --
      Light travels faster than sound. This is why some people appear bright until you hear them speak.........
    23. Re:Something to note about other people's opinions by mini+me · · Score: 4, Funny


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

    24. Re:Something to note about other people's opinions by oliverthered · · Score: 2, Insightful

      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 along with every problem I come across and the possible and chosen solutions.

      I find that a lot more helpful then any comments in the code as it gives me the big picture and tells me why things were done and other ways that they could have been done.

      I can also usually drop any project and pick it up again months later and quickly and easily pick up where I left off.

      If you really want to find out what side effects a function has or how everything hangs together there are tools to do that (or they can easily be written) and they will be more accurate and less misleading than any comments someone can write.

      --
      thank God the internet isn't a human right.
    25. Re:Something to note about other people's opinions by SavedLinuXgeeK · · Score: 3, Interesting

      Yes. Every project I have worked on has had design standards, coding standards, and peer reviews. Yes there were tight crunches on time at many moments, and the quality of code does suffer at those points, but overall the code lives up to the standards and is better for it. It is easier to maintain, debug, update, refactor etc. because it is well designed and implemented. I very well could be an anomaly but I have to believe that in order to ensure that a system requirements were meant (in the form of Ilities) you need to have broad control over the code (how design decisions are developed, and enforced).

      --
      je suis parce que j'aime
    26. Re:Something to note about other people's opinions by networkBoy · · Score: 2, Interesting

      At my old job we re-used code.
      It was written in Borland C 2.0, shoved into 3.0, dragged across to Visual Studio 6, then keelhauled into 64 bit support (from 48 bit initial functionality). We re-used that codebase for every project, tweaking and modifying, forking where appropriate per product family. Management asked what it would take to make it more maintainable and myself and the one other developer still with the company said: 8 months of dedicated time for one of us, with guaranteed time for code reviews of 2 half days per week for the other developer to provide a second set of eyes. Naturally that didn't happen. FFwd a year and the division is being split from the parent company with > 30% layoffs. Upper management decided who went and who stayed with a rather broad brush. Since I was technically "maintenance" and the other developer was old enough to retire we were both cut (she got a carrot to volunteer to retire). So who is developing and maintaining the code now? My old boss. Less than a month has gone by and I'm already getting "helpdesk-ish" calls on the code. Once they are fully split from the parent company (for which I am still employed, but in a different devision now), my consulting rate will kick in, and boy will it be nice.

      Moral of the story: When code *is* re-used, it usually gets ugly. A clean re-write is not always a bad idea, and if your devs are asking to be allowed to re-write something you should let them before you can them...

      -nB

      --
      whois gawk date unzip strip find touch finger mount join nice man top fsck grep eject more yes exit umount sleep dump
    27. Re:Something to note about other people's opinions by coaxial · · Score: 2, Insightful

      Right-o. Too many people don't comment their code at all. I've spent a day before just commenting other people's code, just so that I could begin to know where the bug was. Don't make me figure out what your for-loop is doing. Just tell me. You want your code to be as clear as possible, and comments make the complex clear, and the obvious more obvious -- which is good, because it's obvious that what is obvious to one is not always obvious to another. ;)

    28. Re:Something to note about other people's opinions by SilentBob0727 · · Score: 5, Insightful

      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.

      --
      Life would be easier if I had the source code.
    29. Re:Something to note about other people's opinions by Nevyn · · Score: 2, Insightful

      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 TABs and spaces mixed are the spawn of satan, and given that we can't get rid of spaces getting rid of TABs is the only sane option.

      Macros for integral constants (yes, even in C), since enum does the job and obeys scope (yes, C has different scopes, not just C++).

      What people call C is really two languages, and the pre-processor doesn't understand enums so that's a major reason to use macros instead. This is esp. useful when you are defining an interface and need to expand it (Ie. #ifdef FOO /* code for older interface where FOO doesn't exist */). You can mostly get around this by using enums and then defining macros of the same name to the enums, but that doesn't always work ... or you can just not use enums because noone else does either.

      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.

      While that's a nice goal, it's really really hard to do well. Making a shared library that does X is at least 10x harder than just doing X IMO. ... making it work well can be even harder. And the maintenance burden is probably closer to 100x harder, unless you take the retarded route like OpenSSL and cause everyone using your API massive pain.

      --
      ustr: Managed string API with ave. 44% overhead over strdup(), for 0-20B
    30. Re:Something to note about other people's opinions by Sparks23 · · Score: 3, Interesting

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

      --
      --Rachel
    31. Re:Something to note about other people's opinions by mini+me · · Score: 2

      Also, humans tend to read left-to-right, top-to-bottom. Any worthwhile program is filled with loops, branches, conditionals, calls, recursion, etc.

      You're not executing the code. It's still read left-to-right, top-to-bottom.

      It's not restating, it's clarifying what the code does

      But I'm saying that well written code does not need clarification. When it's well written there's nothing more that can be said in any other language that hasn't already been said directly in the code. I'll admit there are border cases where it's almost impossible to write code that is abundantly clear and under those circumstances comments are a good idea, but those should be few and far between.
    32. Re:Something to note about other people's opinions by SilentBob0727 · · Score: 2

      You're not executing the code. It's still read left-to-right, top-to-bottom. Hell, that can be even more confusing than reading the code the way a computer would.

      But I'm saying that well written code does not need clarification. When it's well written there's nothing more that can be said in any other language that hasn't already been said directly in the code. I disagree. Languages differ in their expressiveness, and sometimes human language can be used to succinctly clarify what may take 200 lines of disjoint, complex code to specify in a computer language.
      --
      Life would be easier if I had the source code.
    33. Re:Something to note about other people's opinions by TigerNut · · Score: 3, Insightful

      When software or firmware is a major component of your commercial output, then it is important enough that it should get as much up-front design, in-process review and documentation as your hardware.

      Doing good software design up-front saves a huge amount of time in writing and debugging. If you're doing an OO project of any significant complexity and you get your class definitions messed up, then the code implementation is going to suck, both in performance and in maintainability.

      It doesn't only apply to big projects. My code is aimed at 1k or 2k FLASH targets... if you don't design it right up front, then it's not going to fit. When you're coding for something that's going to get masked into ROM, you want to be able to show that every line of code has been tested and that there are no degenerate situations. Add to that a realtime environment where you don't know when certain interrupts are going to happen in relation to each other, and proper design becomes the difference between something that works all the time, and something that is dependent on all kinds of seemingly unrelated occurrences.

      --

      Less is more.

    34. Re:Something to note about other people's opinions by Anonymous Coward · · Score: 5, Insightful


      But I'm saying that well written code does not need clarification.

      Here's some well-written code:

                      int nIMin = m_nIMax;
                      int nIMax = m_nIMin;
                      int nJMin = m_nJMax;
                      int nJMax = m_nJMin;


      So is it a bug? I can hear you protest now that you'd need to see it in context to know. But if I add a single short comment:


                      int nIMin = m_nIMax; // initialize to opposite ends of range
                      int nIMax = m_nIMin;
                      int nJMin = m_nJMax;
                      int nJMax = m_nJMin;


      you know that my intent was to initialize max with min and min with max.

      There is no way to express this in the code itself, and this kind of situation crops up all the time in well-written code of even moderate complexity. People with limited imaginations, who lack the capacity to see that their code could be read in many different ways, are generally unable to grasp this point, even when presented with multiple examples. Sad, really.

    35. Re:Something to note about other people's opinions by Brad+Eleven · · Score: 2, Insightful

      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 filenames. It's obvious that the entire list doesn't need to be reprocessed every time, but why stop without processing all of them?

      Ideally, the code itself would contain such rationale as an adjunct to documentation describing how the modules, scripts, etc. all fit together to accomplish some goal. That's what I strive to leave behind--either for someone else, or for myself when/if I encounter my code again years later. I've done this about a dozen times so far, and I usually laugh at what I was thinking "back then." Even so, it's readily apparent what I was trying to accomplish, so that I can either tune it up, fix it, or adapt it to a situation that has changed.

      The most hilarious code I've ever worked on was hand-optimised C, replete with explanations about why the arrayname + offset notation was so much faster than the arrayname[offset] notation. The fellow seemed to have been so proud of himself for that style that he forgot to check the logic. Most, if not all of the comments came across as bragging about how good the code was, sprinkled liberally with the repeated declaration, "CODE IS MORE EFFICIENT!!!"

      The only other comments I really appreciate are those that explain something that might look weird to someone else. I don't mind extra comments so much; they can be grepped out like so much beer foam.

      --
      "Press to test."
      (click)
      "Release to detonate."
    36. Re:Something to note about other people's opinions by dubl-u · · Score: 2

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

      I'm not sure if you're dealing with idiots who are skipping practices or if you just missed the bigger picture, but either way let me explain how that approach can work very well.

      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.

      In those conditions, the bigger picture lives in everybody's heads. You don't write it down because it would be pure waste. The time to document it is when team continuity might be broken. Like when you put a project aside for a while, transfer it to another team, or publish an API. Then you schedule the writing of documentation in the queue with all the other work. That should certainly include a big-picture explanation of the system.

      If you've got good unit test coverage, nobody should be afraid of deleting anything. If the tests fail, you just hit undo. And if you've got good acceptance test coverage, most languages have tools that will let you check for unexecuted code. When I'm working in Java, I use IntelliJ's IDEA, which automatically highlights unreachable or unreached code, which I love.

      Those tests also shouldn't be mere tests. They should be an explanation of what something is for, built around examples that computers can verify. For the developer side, check out the various Behavior-Driven Development frameworks that have appeared in the last couple of years. For the acceptance tests, see FIT, FITnesse, and other tools that are focused not just on testing but on explaining the product.

      The reason Agile people lean away from documentation by default is that documentation is by definition redundant. It's extra work to write, it adds a tax on changing the thing it documents, and it risks drifting out of date. Instead put a lot of effort into making the primary artifacts communicate well (via clear code; great names for variables, methods, and classes; well organized file layouts; clean system architectures; readable tests; and everything else that makes up beautiful code). Every time I get the urge to document something, I first try to make it clearer, so the documentation isn't necessary. When I can't, I document.

    37. Re:Something to note about other people's opinions by kscguru · · Score: 2, Informative
      Because it *can* cause a circular include dependency which is extremely difficult to detect. FooClass instantiates BarClass instantiates FooClass ... kaboom. And it really does cause a large increase in preprocessing times to pull in all those headers, even simple files end up 10,000-40,000 lines after preprocessing.

      That said, I and my coworkers use includes in headers all the time. (ONLY include a header if you need the full definitions; if it's just a FooClass pointer, forward declarations are far better. And don't be afraid to split a header into "foo.h" (struct definitions" and "foo_types.h" (forward decls, typedefs, enums); most clients of the header only need the latter). Writing good code truly is an art form.

      --

      A witty [sig] proves nothing. --Voltaire

    38. Re:Something to note about other people's opinions by Tim+Browse · · Score: 2, Insightful

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

    39. Re:Something to note about other people's opinions by coryking · · Score: 3, Insightful

      I would challenge [the staunch agile supporter] to come up with a "well-written" alternative And your code comments will tell them that you tried to create a well written alternative but it didn't pan out because [insert comment here].

      Besides making up for language deficiencies, most comments should be exactly "this looks bad, but it is the right solution because [insert reason]" or "this code sucks, but [insert reason]". Good comments aren't English translations of the code, they provide the "what I was smoking when I wrote this". Bad comments are "initialize counting variable".

      I should also add that good comments should be written for everything publicly exposed. Good implementations of Intellesense will make life easy down the line by sucking up the comments (or xmldoc for visual studio projects and perldoc for perl).

      Really, this entire debate is an old news. People should really RTFM :-)
    40. Re:Something to note about other people's opinions by SilentBob0727 · · Score: 3, Insightful

      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 management software where everyone is required to read the commit logs seems to work better at fostering a team code environment than pair programming. There is something to be said for an employee having their own space. In my own experience, the only time pair programming has ever worked is in an EXTREMELY small (read: three people) team. It just doesn't seem to scale. Usually someone sits back and watches the other one code, going, "huh?" until they either give up and do something else or have to switch.

      That said, XP has some good ideas (I test-driven development, refactoring) that when combined with the good ideas of the more traditional methodologies (story cards be damned; formal initial design and modeling are important!) create a more flexible development environment.

      Every time I get the urge to document something, I first try to make it clearer, so the documentation isn't necessary. When I can't, I document. I would agree with you. Documentation is not a substitute for poorly written code.

      To put it more succinctly: Quality comments enhance the readability of quality code. In other words, the art of comment writing is just as important as the art of code writing: there are good comments and there are bad comments. A few well-designed comments can go a long way towards elucidating a block of tricky code.

      If you've got good unit test coverage, nobody should be afraid of deleting anything. If the tests fail, you just hit undo. Except when you have a function that's not called anywhere except from its unit test... then if you delete the function the unit test fails! You have to delete the test AND the function and then suddenly you have the same situation of fear of removing two things instead of one.
      --
      Life would be easier if I had the source code.
    41. Re:Something to note about other people's opinions by IngramJames · · Score: 3, Interesting
      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 :)
      --
      'No rational religion claims "supernatural" exists, that's an atheist slander.' - seen on slashdot.
    42. Re:Something to note about other people's opinions by ILongForDarkness · · Score: 2, Interesting
      Wouldn't it be nice if there was an IDE that would allow you to turn on and off comments? Sort of like VS's regions. It would be nice if you had options like, no comments, all comments, only header comments, etc. I agree sometimes you need a lot of comments because the code is doing something really isoteric, and sometimes you want the comments out of the way so you can fit the block on your screen rather than having to remember where you are in the code.

      Yet another interesting feature I'd like in an IDE. Something similar to Excel's freeze panes but dynamic. So it fallows the start of the block, so at the top of the screen you'll have:

      if (blah == run_some_crazy_spagetti) {

      It would make my life so much easier. The closest think I've seen is emacs status bar that will show } // if (blah). I think it makes more sense for the user to look in the intuitive direction (up) for the help on what block they are in not, up and if they don't see it then down.

    43. Re:Something to note about other people's opinions by magical_mystery_meat · · Score: 2, Insightful

      The no-comments maxim of Agile is, frankly, horseshit. Kent Beck came up with it to sell books to people who don't like writing in English. It's nothing but a rationalization for egomaniacs who think they are incapable of writing bad code.

      Do you have a cast-iron photographic memory that can always recall what you were thinking at any given moment, six months later? I know I don't. But most programmers think they're infallible and that their code is perfect. They forget that someday someone else is going to have to work on this stuff, and what makes sense to you will likely be complete gibberish to everyone else.

      I've seen the long-term effects of this philosophy and it's not pretty. I recently worked in a mature (4+ years) codebase that had been Agile from the start. It was a horrible, convoluted morass of spaghetti, mixing poorly designed classes and refactored-to-metrics code that used 10 methods and 5 classes to do what one sanely designed method would do. There were massive bugs that nobody could find, the code was inefficient, it took a good six months to get the best people in town trained well enough to work on it (and this place hired all contractors so they were writing their code as flashy as possible to show off just in case the other guys on their team happened to interview them for their next assignment).

      I won't consider many programming practices to be completely invalid, but refusing to comment is one of them, and I will not work in such an environment again. It is a sign of stubbornness and hubris and neither of those are agile states of mind.

    44. Re:Something to note about other people's opinions by Beardo+the+Bearded · · Score: 3, Insightful
      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".
      --

      ---
      ECHELON is a government program to find words like bomb, jihad, plutonium, assassinate, and anarchy.
    45. Re:Something to note about other people's opinions by fbjon · · Score: 3, Insightful
      That's not the worst problem with the code, my immediate question was "what is v, and why do we want to put several doubles in it?". It's like reading a suspense thriller, the ending provides the explanation. A single line comment at the start: "//Read in doubles and print in reverse order" would give all the explanation needed for anyone to figure out what happens, even for someone who's never seen C++ before.


      Moreover, single-character variables outside the scope of a loop should be banned from the face of the earth. It's all right to use them when coding, but when the coding is done, for god's sake rename then to something sane.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
    46. Re:Something to note about other people's opinions by nahdude812 · · Score: 3, Insightful

      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.

    47. Re:Something to note about other people's opinions by nonsequitor · · Score: 2, Insightful

      do people out there really have TIME for coding methodologies, reviews and the like?
      You have to make time for the important stuff, its not finished until all the i's are dotted and the t's are crossed as far as management is concerned. The alternative is much worse, let me describe a typical scenario for you.

      Let's say you rush through and get some code that "appears" to work, you tell your boss "Good news, the code works." The next thing you know you need to have it to the customer tomorrow. Turns out your code is a mess, nothing has been thoroughly tested and it breaks when the customer tries it.

      Your boss is pretty upset at this point, you've just embarrassed your company in front of a customer. You work with the customer find out how it broke, fix it with a hack, knowing you'll clean it up later and send a new version to the customer. You still haven't fully tested it at this point, but thats okay because they needed this last week.

      The software breaks again, the cycle repeats a few more times and now you have something which is stable. You ask your boss for time to clean up the hacks, he says no, I have another project for you. A month later the software breaks again, to fix it you realize you have to rewrite the whole thing because the lack of proper design and hacks layered upon hacks make it necessary to do major rework.

      By the end of all this you've lost a customer, they've decided that the price of doing business with you is too great because you're unable to estimate how long and how much a job will really take, and it interferes with their business.

      Now consider the alternative, you throw together some code that works and tell your boss "Don't worry, I have some proof of concept code finished and it will take only 3 more weeks to finish this project." You use that code as an example and design, have design reviews, code, have code reviews, and do unit and integration testing. When you deliver it to the customer, it works, is robust, and you have a happy customer.

      As a programmer, it is your job to properly manage the expectations of those around you so that plans can be made around your deliveries. If your code always works when delivered, as opposed to almost invariably having easily exposed bugs, you build a reputation for being reliable and having accurate estimations. Sure it takes longer, but a few extra weeks up front can save months of time down the road.
    48. Re:Something to note about other people's opinions by famebait · · Score: 2, Informative

      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 can make it necessaary to cut corners, but make it clear that this way of working insults you (not for aesthetic reasoons, but because it's wasteful ands stupid). But you can get away with a lot of best-practice work if you stay focused and don't start adding stuff you don't need. And it usually takes less than days for tidy code to pay off, so unless someone is peeking over you shoulder, you might not even have to defend it. _Never_ do anything "quick-and-dirty". There will never be an 'afterwards' in which to tidy up. If it's worth doing, it's worth doing properly. What you _can_ (and should) do is "quick-and-_simple_": cut features to the bone until you need them. Don't be tempted to make framework when what you need is a function. But be ready to refactor it out (to the germ of a framework) when a more general version is needed. It sounds like more work, but it usually isn't in reality, and there's less code to debug later, and you won't introduce bugs when one implementation changes and the other does not. This, again, has noticable effect even on the scale of days.

      To the parent:
      I agree that proper API comments are essntial, but faced between a well-commented but ugly API and a well-designed, well-named and consisten one with only minimal comments, I'm not sure I'd always take the well-documented one. Especially not if the code inside is clean enough to worthy an little look.

      But when it comes to commenting internal code, a rally good habit is to rough out the general structure in a coarse pseudocode of TODO comments before coding, and then fill in the blanks, removing the TODO tag but leaving the text as a heading as each block is completed. And adding new todos as you think of stuff as you go along. That way the commenting becomes not a chore but a _really_ useful aid in you work, helping you think clearly and reminding you of context even when littel code is written yet. And of course, when it _saves_ work in stead of adding it, it becomes a lot more likely to get done, too.

      This comment style goes very well with another good practice for readable code, that probably has another name but which I call "bailout" logic:
      Use guards of various types to throw out pathological or skip-cases as early as possible (throw exceptions, use 'return', 'break', and 'continue') in stead of nesting everything that actually happens deep inside multilevel if/else/switches, or constructing complex or clever (a.k.a. bug-prone) condition statements.

      This makes for a nice, 'story-like' read for the 'normal' or most intersting flow. It will often be a good idea to add a brief comment after such a bailout (or the block it is in), stating the precondition that has now been met by virtue of getting here.
      Some people oppose this style, since you have exit points all over the place in stead of everything merging at the end. I will gladly trade that for making it _much_ easier to get a clear picture of what kind of state I'm in when I actually reach some interesting code. And you simply have less cases to worry about for most of the code.

      Sometimes, if neither 'while', 'for' or 'do-while' _really_ map all that well to your actual loop logic, you can be a lot more by understandable with "while true", and then break or continue explicitly where they fit naturally in the sequence, in stead of forcing it to the start or end (or *shudder*, abusing the increment statement to do actual work)

      --
      sudo ergo sum
    49. Re:Something to note about other people's opinions by tilde_e · · Score: 2, Insightful

      How about int nReversedIMin = m_nIMax; for starters? Do you really believe a single line comment that could be 40 lines above the code that uses nIMin is sufficient? Adding the comment there just says "I intentionally made this code confusing. Good luck."

      I think if you relax your absolutism a little you can find better solutions.

      (BTW, m_ is a very weak convention. 'this' is much more clear and some compilers can enforce that you *must* use it -- Eclipse/Java project settings for example. I've also seen someone prefix every function parameter name with 'arg', what is that about? Talk like a pirate day?)

    50. Re:Something to note about other people's opinions by JavaRob · · Score: 3, Informative

      But I'm saying that well written code does not need clarification. When it's well written there's nothing more that can be said in any other language that hasn't already been said directly in the code. I'll admit there are border cases where it's almost impossible to write code that is abundantly clear Have you never been brought on to maintain a large codebase that you didn't write? Even if it's *beautifully* elegant and refactored to a sparkling shine of perfection, you're still going to be lost in large sections of it for a while. There's going to be project-specific terminology decided by the developers in variable & class naming that you'll have to learn, and you simply cannot always glance at a single shard of an enormous project and comprehend where it fits into the whole. Ideally, you're going to have a whole lot of relatively independently functioning little parts, right?

      Suppose you have an exception raised in a given class. You know the line number, and you open the class... if it's involved in serving a purpose that's low-level enough, it's going to take you a far more time to figure out what it's for, how it's used, and what role it plays in the project as a whole if you don't have, say, 3 simple lines of plain English in the header comment.

      Personally I don't write too many comments in my "normal" code. I write progressively more as the code gets more complicated -- some features are simply too complex to even fit the implementation in my head all at once, so I write a shorthand walk-through of the implementation before I start. When I'm done, sometimes the code has actually boiled down enough that I can chuck that (sometimes I'm not so lucky).

      You have to comment implementations that "look wrong" or are counter-intuitive, possibly because of client demands ("the last software package did it that way, so our other systems are designed to correct for it..."). What, are you naming methods calculateScaleWronglyPerClientRequest()?

      It can be wise to flag methods (or classes) that will *appear* unused to refactoring analysis, because they're loaded & accessed dynamically.

      I could go on.
    51. Re:Something to note about other people's opinions by Mr2cents · · Score: 2, Insightful

      It's more intuitive to find that programmers lack the TIME to just think. Courage has nothing to do with it.
      The longer ANY programmer spends on the same code, the better it gets designed (if not written).
      Really good programmers criticize themselves as they write and are almost never happy with a refactor. All three statements are correct. However, I fail to see the connection between them, and I'm not really sure where you're going.

      Let's just start at the beginning. Do you really think I don't have deadlines too? Yet, while the rest is panicking, I'm taking a walk through the building, or looking through the window. I refuse to start coding right away. To me, this pays off: Once I have figured out exactly how I am going to tackle the problem, I need to write less code, debug it less and once it is in the field, I don't get as many support calls as some of my collegues. I get the job done and the customer is happy. But should you measure my productivity by how much code I write each day, I would be a lousy programmer. This is exactly what I mean by courage: in the face of deadlines, mass hysteria, panic and worried bosses, you need to sit back and relax.

      Your second statement is beating a dead horse.

      Your third statement... I don't know how you got there. Where did refactoring enter the discussion?

      I'm not sure how that is helpful advice. You can't know how simple you can make something without usage. We come back to spending time reworking something you've already written. Once you see how other people (or just yourself) need to use it in the real world, you know how complex it *NEEDS* to be. Programmers are generally lazy and do not write things more complicated than necessary. When you start out sometimes it can get out of hand, but you come back to reality or dont ever come back. /For who, exactly, was that advice...insightful? What I do is I write an as simple as possible API, and I pretend it is already implemented. Then I can use it in the rest of my code and if it is insufficient, I rethink the API. Of course you cannot always foresee all the neccesary functionality beforehand, but that's something everyone has to live with. If you know a way to make a completely stable API right from day one, I'm very curious to know.

      On the other hand, if you constantly need to change the API, it's a sign you haven't clearly defined what you're willing to abstract. Again, thinking about the problem will make it clear what you need and in 80% of the cases it will do fine without modification (rough estimate from personal experience).

      And if you think everybody writes code as simple and short as possible, you're either not very experienced, or else I want to work where you do.

      PS: I could be wrong, but from the tone of your post I conclude that you consider me some sort of babbling fool. Let me assure you, I'm not - at least not on this subject. Sorry if I sound arrogant (hey, you started it), but my IQ is 135, I've been programming for over 20 years now, and I really, really know what I'm doing. Don't mess with me ;-).
      --
      "It's too bad that stupidity isn't painful." - Anton LaVey
    52. Re:Something to note about other people's opinions by Chemisor · · Score: 2, Interesting

      > Just nitpicking. If you're going to use a bad practice, at least use it well.

      Since we are nitpicking, I would say that I do not use hungarian notation. It assigns variable names based on their type; I assign variable names based on their expected usage and their scope. For example the m_ prefix tells me where to find the variable, rather than what it is. I would also use type prefixes in cases where they say something important about how the variable is used. For example, "m_pDocument" is a better name than "document" because it explicitly tells me that this object does not own the document, and that the variable is to be used with -> instead of ., which is not always obvious. Other type prefixes can be used if they serve the same purpose. And as for the full hungarian notation, I'd say that m_lpszName does way more harm than good.

  2. Same here by polar+red · · Score: 4, Insightful

    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.

    --
    Yes, I'm left. You have a problem with that?
    1. Re:Same here by ByOhTek · · Score: 2, Insightful

      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 you think otherwise, you need put your arrogance in check so that you can produce useful quality code.
      3) The customer, in the interim, still knows their situations and setups better than you in most cases. While they may need to change requirements for overlooked circumstances and situations, that doesn't mean they don't know what is going on.
      3.a) Pointing out that they have missed something isn't necessarily a bad idea though, if you do it in a respectful manner. This can actually improve their perception of the quality of your work.

      --
      Self proclaimed typo king, and inventor of the bear destroying coffee table (patent not pending).
  3. Getting better. by Ihlosi · · Score: 4, Informative
    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.

    1. Re:Getting better. by RandoX · · Score: 3, Informative

      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.

  4. More Design by Loophole64 · · Score: 3, Informative

    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.

    1. Re:More Design by 0xdeadbeef · · Score: 2, Insightful

      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.

    2. Re:More Design by Oligonicella · · Score: 2, Interesting

      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 becoming concerned and thinking it's a waste. It's actually a method for speeding things up towards a positive end.

    3. Re:More Design by Foolicious · · Score: 4, Insightful

      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!

      --
      Please don't use "umm" or "err" or "erm".
  5. You have to communicate by MosesJones · · Score: 4, Insightful


    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.

    --
    An Eye for an Eye will make the whole world blind - Gandhi
  6. The virtue of constraint, and other musings... by Max+Romantschuk · · Score: 5, Insightful

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

    --
    .: Max Romantschuk :: http://max.romantschuk.fi/
  7. Apples/Oranges by ilovegeorgebush · · Score: 3, Insightful

    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.

  8. Worse Than Failure by Rik+Sweeney · · Score: 2, Funny

    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.

    That said, I do revisit code that I'd written a few years back and think "WTF were you thinking?!"

  9. Management by Algorithmnast · · Score: 2, Informative

    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 as a model of our software development "practices".

  10. Be proud of the work, not the code by PIPBoy3000 · · Score: 4, Insightful

    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.

    1. Re:Be proud of the work, not the code by oliderid · · Score: 2, Insightful

      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.

  11. TIME! by microTodd · · Score: 3, Interesting

    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.

    --
    "You cannot find out which view is the right one by science in the ordinary sense." - C.S. Lewis on Intelligent Design
  12. Lost out by gaou · · Score: 5, Funny
    "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 :)

    1. Re:Lost out by bhaak1 · · Score: 2, Insightful

      Just for the record: AmigaBASIC was my first real programming language (LOGO on paper doesn't count).

      That you don't know this quote (it's from 1975 BTW) and have been to the university just shows how much CS is a science without respect for its history.

      That you don't have heard of Edsger W. Dijkstra is shame.
      http://en.wikipedia.org/wiki/Edsger_W._Dijkstra

      Tell me, do you consider the GOTO command harmful?

  13. Work for engineers not software companies by Hektor_Troy · · Score: 2, Interesting

    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

    --
    We do not live in the 21st century. We live in the 20 second century.
  14. Do some open-source coding to feel clean again. by Dr.+Manhattan · · Score: 4, Interesting
    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.

    --
    PHEM - party like it's 1997-2003!
  15. All Code Sucks... by iBod · · Score: 2, Interesting

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

  16. Code is communication by Dystopian+Rebel · · Score: 4, Insightful

    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.

    --
    Rich And Stupid is not so bad as Working For Rich And Stupid.
  17. Takes a group to judge an individual by eebra82 · · Score: 4, Insightful

    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.

  18. TCO by devnullkac · · Score: 2, Informative

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

    --
    What do you mean they cut the power? How can they cut the power, man? They're animals!
  19. Here's a start to better code by Man_Holmes · · Score: 2, Insightful

    My advice would be to read The Pragmatic Programmer book by Hunt and Thomas. It provides the best blue print I have seen to solving the problem for you.

    You may not be able to implement all the changes at once but you will find that you've got more authority than you realize.

    You may not even agree with all of it, implement what makes sense and your code will improve. I've found with my friends that the longer you've been coding the more sense that the book makes.


    Man Holmes

  20. Yes by Average_Joe_Sixpack · · Score: 5, Funny

    I often use "Programmer: Alan Smithee" in the comment header

  21. Yes, yes and yes by YeeHaW_Jelte · · Score: 3, Insightful

    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.

    --

    ---
    "The chances of a demonic possession spreading are remote -- relax."
  22. after 8 years of professional coding... by w4rl5ck · · Score: 4, Insightful

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

  23. Pride fades with time by Opportunist · · Score: 4, Interesting

    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.

    --
    We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
  24. To be honest? by stonecypher · · Score: 2, Informative

    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.
    --
    StoneCypher is Full of BS
  25. Actual Software Engineering by TheSciBoy · · Score: 3, Interesting

    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.

    --
    Badgers, we don't need no stinking badgers! - UHF
  26. good luck by jmyers · · Score: 2, Interesting

    "Has anyone convinced their superiors that the customer isn't always right and saying no once in awhile is the best course of action?"

    Good luck with that one. Successful technology companies use pie in the sky marketing. Reality does not sell. When you are not saying yes I can do it faster and better then you are whining as far as CEOs are concerned.

    I have a great career and made lot of money writing crappy code. My bosses have always loved it because I am fast to produce an end result. I call it prototyping and constantly remind my employer that I am creating a demo of what can be done. But in the end the demo always goes into production. I have seen several programmers much better than I get fired because they could not bring themselves to lower standards. I guess I'm just a code slut.

  27. The normal response of an inexperienced programmer by petes_PoV · · Score: 4, Insightful
    .. 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.

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
  28. This might be harsh, but the solution is easy... by Caine · · Score: 2, Interesting

    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.

  29. Always write code... by ebbe11 · · Score: 4, Funny

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

    --

    My opinion? See above.
  30. The 2 strongest defenses by sjames · · Score: 2, Informative

    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. In turn, this will result in crappy code since the project will suddenly be late and go from profitable to a net loss.

    OTOH, if you gracefully hear the customer out, then produce a change order for them to sign which outlines how much longer it will take and how much more it will cost, all is well. They'll either tell you to forget about the change or they'll approve it and the extra work is extra profit. There may be a few customers who will cancel the project in a huff, but that was their choice to make. At least you don't get the reputation for producing fragile bug ridden unmaintainable junk.

    A useful rule of thumb there is that if you can accomplish the change more uickly than you can produce the change order, just do it to keep the customer happy. If that encourages them to bury you in trivial changes, you can always gather them up into a change order at that point and explain that the project is now too far along to trivially make those changes.

  31. Perspective and Experience by martyb · · Score: 3, Insightful

    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.

  32. Development Methodology by inKubus · · Score: 2, Interesting

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

    --
    Cool! Amazing Toys.
  33. Actually... by RingDev · · Score: 4, Insightful

    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

    --
    "Most people in the U.S. wouldn't know they live in a tyrannical state if it walked up and grabbed their junk." - MyFirs
  34. Occasionally I ... by kcdoodle · · Score: 3, Interesting

    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.

    --

    - I live the greatest adventure anyone could possibly desire. - Tosk the Hunted
  35. Sorry, I have to bite about this. by Fross · · Score: 5, Informative

    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.

    1. Re:Sorry, I have to bite about this. by SilentBob0727 · · Score: 3, Insightful

      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 extent, "how" (if the how isn't plainly obvious).

      I think the "if in doubt, comment" suggestion is actually bad advice. It leaves people thinking, "God, I really should write a comment here, but I just don't know what would make this line any clearer." Crap like "// create an integer and add two to it" comes about as a result.

      >> It's said comments are like sex - even when they're bad, they're still pretty good.

      I would suggest over-commenting is like having sex while watching a porno -- great at first but after a while it becomes a distraction. When comments are well written, it really becomes a case where less is more.

      --
      Life would be easier if I had the source code.
    2. Re:Sorry, I have to bite about this. by macrom · · Score: 4, Funny

      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.

  36. legacy by suitti · · Score: 3, Interesting

    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.

    --
    -- Stephen.
  37. Not quite true by Moraelin · · Score: 2, Insightful

    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 block with 10 cases is really all you need, you know? His programs tend to be compact, work and be actually fairly easy to get the hang of.

    - one of them is, well, pretty much the opposite. His programs tend to be a lot larger than they need to be, and have layers upon layers of patterns even to print "Hello World". With some reflection thrown in for good measure. Strangely enough, though, they _are_ well organized, and you can fairly easily find the class that processes a given event or command... or the singleton factory that supplies it, or the manager class it's registered with, or...

    Are they perfect according to my tastes? Nope. But I can nevertheless tell good code when I see it, even if it's not perfect. And say it.

    On the other hand, at the other end of the spectrum, I've had to deal with pieces of code which were truly atrocious. E.g., one particular program not only raped all best practices known to mankind, but also was living illustration of half the techniques from How to write unmaintainable code. Literally. It even had stuff like the using people's first names for variables, in addition to the more mundane techniques like mere undescriptive names, obfuscated flow, heavy use of global variables, non-obvious side-effects to those variables, or methods which can also do some 2-3 other unrelated things if called with the right parameters. And I don't mean just side-effects or cramming more functionality in one call than expected. I mean stuff like the class which should have normally sent an email, could render and print a PDF _instead_ of sending one email, or update the contract in the database instead. And for bonus points, not even determined by parameters, but by the contents of those global variables. But, again, the nicest touch was finding uninformative variable names like Pete and Eve in the very first class I opened.

    Basically IMHO lumping it all into one everything-is-the-same "all programmers hate each others' code" pool doesn't do it justice, and paints a misleading image. _Some_ may be just nitpicking about the style, but some code is genuinely evil stuff that should be buried at crossroads with a stake through its chest.
    --
    A polar bear is a cartesian bear after a coordinate transform.
  38. Ah, kids these days... by Moraelin · · Score: 3, Funny

    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.

    --
    A polar bear is a cartesian bear after a coordinate transform.
    1. Re:Ah, kids these days... by LiquidCoooled · · Score: 2, Informative

      Sounds cool, the guy isn't called Mel by any chance is he?

      --
      liqbase :: faster than paper
  39. Re:My code is ok by cayenne8 · · Score: 2, Insightful
    "He also happens to be the one that signs my paychecks. So, there is only so much I can do."

    You know...I 'used' to get all upset about office politics...how requirements were screwed, this...that...etc.

    When I finally realized that is the job is ONLY a paycheck...it is not my life, it is not even remotely a personal thing, just business and a paycheck....my life got much easier. I'll do what they want, I'll change what they want to the best of my ability, in the end, all that matters is getting a paycheck, the bigger the better.

    This also helps to realize, there is always another job willing to sign a paycheck for you...you are not stuck, if someone offers me more $$, I will immediately go that way, no malice, it is all just business.

    Once you can get into that mindset, your life will be much better, less stressful, and you make more $$ as you go along.

    --
    Light travels faster than sound. This is why some people appear bright until you hear them speak.........
  40. Excuse me if I'm rambling, but... by djasbestos · · Score: 3, Interesting

    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.

  41. Re:The normal response of an inexperienced program by 0xABADC0DA · · Score: 2, Insightful
    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 and naming: The code is roughly at your same level of ability. You can understand it and modify it, but you don't want to because it smells bad.
    * High-level structures: The code is written by a more skilled programmer. You probably do not understand why the code was written as it was even with documentation, and even if you do then changes you make will cause a lot of side-effects and unexpected errors. Sadly you should rewrite this code because you cannot make other than superficial changes since you fundamentally do not understand it.

    Generally the code is at the lowest level you are complaining about.

    Another common trait is to deny one's own faults. First of all, if somebody says something is "equally likely" as something else that's almost always some kind of rationalization. There are precious few things that are equally likely (or fair and balanced), and in this case any decent programmer should be able to determine immediately if there are some few ugly sections vs the whole program being a huge pile of crap.

    Of course the BIG mistake is to only have one programmer. What happens when they take a break or leave? Everything stops. Another mistake is to have programmers of very different talent (as opposed to experience) working together. This invariably causes the very talented ones to leave and the poor ones are left with code they don't understand.
  42. In 2 letters... by worldcitizen · · Score: 2, Informative

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

  43. That's Not Good Code by severoon · · Score: 5, Interesting

    The biggest thing I see wrong with other people's code is not at the syntax level or to do with commenting. It's based on a misunderstanding of basic CS principles. An example is in order from last week...

    In the codebase I work on, there's a module that analyzes documents and tags them, assigning different weights to each tag based on relevance. (Think of the way google works--it reads a web page and tags it with terms, then if you type in one of those terms while doing a search that document comes up--yes I know this isn't the way google actually works, save it. :-p ) At one point we send a list of tagged documents from one system to another, and this area was the source of many, many bugs. The responsible developer spent the better part of last week slaving on this code and every change seemed to introduce more bugs than it removed. Finally, I got involved to see what the problem was.

    Here is one thing (out of many) that I found. After the docs arrive in the new system, each doc is supposed to be persisted along with the top 5 most relevant tags (the rest discarded). The code was written to create a Document, check a hash table that maps the doc to the number of tags it currently has, add a tag if that doc doesn't yet have five, then increment the value associated with that doc in the hash table. When I saw this, my head almost exploded. At some point, this developer thought it would be a good idea to create a hash table and keep this information, information which is available in the document itself (he could've just called doc.getTags().size() to see how many tags it currently had). Now he created this hash table and all his code was written to depend on it, so of course he had to write a lot of code to keep it in sync with the state of all these documents.

    This sounds like a simple enough thing, right? It's not necessary, and it's not the best thing, but it's a fairly simple mistake and one that couldn't impact code readability all that much, right? Maybe--but consider that this is one of about 10 simple mistakes I found, and you can imagine the explosion of interactions of all these simple mistakes...and that's why we burned a person-week on something that should've been trivial. When I pointed out to this developer that he could just get the number of tags directly from the doc itself, and doesn't need to keep this state in some other object too, he said something to the effect of, "That's a different approach, but whatever...one's not better than the other."

    But one is better. If this developer understood the difference between intrinsic and extrinsic, he never would've written that code in the first place much less defended it. To put a fine point on it: the number of tags associated with a document is intrinsic to the document itself, so that is where the information should live...not there as well as some hash table somewhere. The document is the authority and the final word on how many tags it has at any moment in time. (There's a principle in databases called the SUA Principle--it means one should keep data in a Single place, in an Unambiguous manner, and that should be the Authoritative source of that data and no other. It applies here too.) Putting this info into some other object, even if that object exists solely for the purpose of tracking that info, means you're creating an object that stores information that is extrinsic to it. Never a good idea...now you need a whole bunch of supporting code that keeps the extrinsic info in sync at all times.

    Let's say I'm designing a Ball class for use in a physics application that students learning physics can use. They can shoot the ball out of a cannon, put it under water, in deep space, on Jupiter, etc, and see how the simulation behaves. As the developer of this class, I decide to add a characteristic to the ball that keeps info about its "heaviness". What should I add, a getWeight() method or a getMass() method? The developer I was talking t

    --
    but have you considered the following argument: shut up.
    1. Re:That's Not Good Code by severoon · · Score: 2, Informative

      Though I'm sure you can design a particular application in which a square is behaviorally a rectangle, and therefore it would be ok to have square extend rectangle, it is not universally the case.

      One of the best things I ever did was head over to Object Mentor's published articles page and click on the Design Principles category. There you will find a paper on the Liskov Substitution Principle which defines exactly when it is appropriate for one class to extend another. (You won't go wrong reading all the papers in that Design Principles category—I found them riveting for hours on end.)

      In this particular case, behaviorally speaking a rectangle has two degrees of configuration freedom whereas a square has one. So, if you think about the actual practice of defining a Rectangle API with get/setWidth() and get/setHeight() methods, you could then write a unit test against those methods to fix the proper behavior of a rectangle. One of those unit tests might go something like: {1} set width to 1, (2) set height to 2, (3) assert that getArea() returns 2. I challenge you to now implement the subclass of rectangle called square that will pass this unit test which behaviorally (and correctly) verifies rectangle-type behavior.

      Your suggestion of making squareness an attribute of rectangle is interesting and one I have not yet heard in any of the instances I've presented this example. I imagine it would take the form of something like the method boolean Rectangle.isSquare(), and would return getHeight()==getWidth(). This would work, as long as clients to the rectangle API understood that its square-ness is temporally defined and could change in the next moment. This is, however, an important consideration, though. In making this a requirement of what it means to be a square, nearly all definition of the square is itself lost...the concept of a square becomes a temporal thing itself. The old mathematical standby of an object that forever and always has equal sides is no longer relevant to this implementation.

      --
      but have you considered the following argument: shut up.
  44. Patterns dodn't work by Tablizer · · Score: 2, Interesting

    Patterns were developed to create a common ground where people can think about problems in a similar way.

    I don't think that's worked. If anything, they've just created more confusion and more ways to head down the wrong path. The more experienced developers merely call them "suggestions to consider", not a central bible of truth.

  45. Re:My code is ok by coryking · · Score: 2, Interesting

    It is not that I don't care, it is just I've had to train myself not to care.

    Nobody else but me takes any pleasure in good clean code, so I really shouldn't care much either. Honestly, there is very little business case for good clean code. You never see products that have "Now With 75% more clean code!" on their cover, do you? People dont pay money for that. They pay for "Now Solves 75% more Pain!". In other words, refactoring, rewriting, or optimizations are all cost centers that should be minimized. They do not directly add to a companies bottom line. New features do.

    That isn't to say clean code is bad; create an unstable buggy app because your code sucks and you'll loose money. The trick is finding the minimal amount of "good clean code" you need to write to make your userbase happy. Anymore and you are wasting resources.

    I'd argue if your paycheck is tied to some nebulous idea of "good code" is getting rewarded wrong. Your paycheck should depend on another, equally nebulous notion of "good user experience". I'd rather you write a nasty hack job that makes everybody smile when they use your application than a hard to use application that pisses everybody off, but has "good code" in it.

    Good Code is code which creates a happy user. No other definition should be allowed.

  46. Re:comments are important by thejuggler · · Score: 2, Informative

    I fully agree - Having well worded comments is just as important as well thought out code. There are many times when I am debugging a piece of code and I know what the code is doing by reading the code, but since there are no comments I have no idea what it is supposed to do. And if you have to work on code that is not documented anywhere , except in the murky gray matter of someone that thinks they remember telling someone to write something, the in-code comments become essential.

    I typically preface my more complex code blocks/functions etc with a brief algorithm this way someone in the future knows what I was intending to write and well and when I am writing I can verify that my code does what my algorithm says. This sort of documentation also helps clarify the task and helps define all possible logic scenarios. This way you can write a more complete, stable piece and possible bug free (yeah right) of software.

    This is just a mature way of programming.

    P.S. - I never claim someone else's code sucks just because they don't have my 'style' of coding. I just want the code to work properly.

  47. Customer = Wrong by 7Prime · · Score: 2, Interesting

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

    --
    Multiplayer Gaming (defined): Sitting around, discussing single-player games with my friends, at the bar.