Slashdot Mirror


What Workplace Coding Practices Do You Use?

Agent_9191 asks: "Recently I've been promoted to what essentially amounts to a project lead role for every project we do, in house. Since my company has run for the past 35+ years with no form of central IT department, there has been no standards put into place for developers to abide by. One of my tasks is to set up standards in how projects will be implemented and produced. Right now I'm more concerned about trying to set up coding standards, so that any developer can jump into any part of a project and be able to figure out what's going on, without wasting a couple hours just to figure out the code. I've come across some documents in this area from a few sources (of course can't remember them off the top of my head). What practices/standards do you use in your workplace?"

151 of 682 comments (clear)

  1. Comments by Gyga · · Score: 5, Insightful

    Tell them to use comments in code, and be sure that they make them good comments.

    --
    I don't preview or spellcheck.
    1. Re:Comments by mopslik · · Score: 5, Informative

      ...be sure that they make them good comments.

      And make sure they update comments if changes necessitate it. There's nothing worse than reading through a function's description, complete with well-documented inputs/outputs/conditions/etc. and finding out that those things no longer apply because somebody changed a 1 to a 2.

    2. Re:Comments by Threni · · Score: 3, Insightful

      > somebody changed a 1 to a 2

      You shouldn't be using magic numbers anyway - use a #define so that the comments and code stay the same regardless of what the value happens to be.

      Instead of

      function(1);

      try

      #define LOAD_DATA 1

      function(LOAD_DATA);

      Then you don't need to care what LOAD_DATA is.

    3. Re:Comments by Py+to+the+Wiz · · Score: 5, Insightful

      "if x==456 then //checks for conditional x and executes code if x is true - this is not a good comment if x==456 then //checks to see if x is equal to 456."

      Actually, IMHO, those are bad comments. Too much commenting, while not as bad as too little commenting, is still a problem. Writing too many comments is not only time consuming for the developer, but it makes it harder to find the important comments in the sea of crap. Also, if the program is modified, all the comments must be changed as well. This can be a tedious and time consuming process for large projects.

      Personally, I try to use comments for parts in the code that might be confusing. Even for a novice programmer, code like if(x == 456) is self-explanatory, no comments are needed. But complicated statements involving many different variables from different parts of the file may be confusing, and likewise merit comments. Also, comments with input/output or precondition/postcondition for functions might not be a bad idea either.

      Use comments when you need them, but don't write so many comments that they become useless.

      --
      Fight the fall of slashdot by supporting PlayfullyClever in your sig.
    4. Re:Comments by Seraphim1982 · · Score: 3, Insightful

      I would say both of those are bad comments. Neither of them tells me something that a very basic understanding of the language wouldn't tell me.
      I would say a good comment (that is, a comment that I would find useful) for that piece of code would tell you why the statement was important, what is it going to accomplish, and if needed why was it writen the way it was. For your code my questions when reading it would be "why 456?" and "what is going to happen in the following block(s) of code?".

    5. Re:Comments by republican+gourd · · Score: 5, Insightful

      Has anybody written an IDE plugin yet to sign comments? You could for instance have a hash that uniquely identifies comment lines 10-20 and code lines 30-70 as the a 'set' of data that is required to match. Then if the hash of either section changes, flag it as a problem until the hash is regenerated.

    6. Re:Comments by jomegat · · Score: 5, Insightful
      BOTH of those comments are bad. If a person knows relatively little about programming, he shouldn't be in a position to modify your code. If they don't know what an "if" statement does, they have no business mucking around in my code anyhow.

      Comments should concentrate on "why" not on "what." A machine can figure out "what," so a programmer should be able to do that too (eventually). No machine has a clue as to "why" though.

      Any time I'm reading through my code and I can't remember why I did something, it's a red flag - that needs a comment. If the code doesn't look like it's needed, but it really is, you need to put in a comment explaining why it's there.

      "What" comments should be reserved for the top of a function or largish body of code.

      --

      In theory, practice and theory are the same. In practice, they're not.

    7. Re:Comments by dorkygeek · · Score: 5, Informative
      For example:
      if x==456 then //checks for conditional x and executes code if x is true
      - this is not a good comment
      if x==456 then //checks to see if x is equal to 456. If it is, then the code within is executed
      -this is a good, easy to understand comment.

      Is this supposed to be a joke??! Both of them are worst comments, because they only formulate in english what the code already says by itself. Everyone can see that this is an if-statement, everyone is able to identify the condition, and everyone knows the semantics of an if-statement.

      A good comment is not describing what is done (since everybody can see that from the code itself), a good comment describes why something is done, or what the overall objective of the statement is.

      For example:

      if (x == 456) { // Check if step motor reached final position. If yes, halt motor, otherwise step forward.

      This is ways more useful. Even more useful would be to already use self-describing symbol names in the code itself, like

      if (currentPosition == finalPosition) { ...
      --
      Windows is like decaf - it tastes like the real thing, but it won't get you through the day.
    8. Re:Comments by joe_bruin · · Score: 4, Insightful

      Our coding standard is a little like this:
      Write clean code that can be easily understood by reading it. That is, good variable and function names, try not to make any absurdly complicated statements, and have your comments explain the logic of the operations. As for style, try to stick with the style that the original author started with. And finally, all people who use Hungarian notation are locked in the basement and given menial tasks until they repent their sinful ways.

      I hope this helps.

    9. Re:Comments by NemoX · · Score: 3, Interesting

      Visual Studio has one called "Ghost Doc" that we use. Also, microsoft has some macros you can download that will create documents for constructors and for any exception within a method. Using these two together, and you have a pretty standardized comment collection that can be compiled by NDoc (the .NET version of JDoc for Java). I have a really good one for Eclipse, also, but can't remember it of the top of my head.

    10. Re:Comments by OzRoy · · Score: 2, Insightful

      This is something that seems to be very common in commenting. Comments are not there to describe every line of code. Any programmer can see what the code is. A good comment should explain *why* it is that. It should explain what the input is, and what the final output should be.

      I looked at that if statement and wanted to know why 486? Why does it execute that block if x is 486? That is what the comment should do.

      That said I really need to comment my own code better than I do :)

    11. Re:Comments by naibas · · Score: 5, Informative
      Both of them are worst comments, because they only formulate in english what the code already says by itself. Everyone can see that this is an if-statement, everyone is able to identify the condition, and everyone knows the semantics of an if-statement.

      A good comment is not describing what is done (since everybody can see that from the code itself), a good comment describes why something is done, or what the overall objective of the statement is.

      Amen to that.

      In addition to the original comments being redundant, there's also the issue of the code and the comments getting out of sync...

      The company I work for just wrote up a formal coding standard, which includes everything from a guide to our internal hungarian notation, indentation guidelines, and even which C++ features/paradigms are supported, frowned upon, or not allowed. All the coders got a chance to send in feedback before it was finalized, and we even ended up with a list of recommended reading on the subject, including:

      • Sutter & Alexandrescu's C++ Coding Standards,
      • Meyer's Effective C++,
      • Meyer's More Effective C++, and
      • McConnell's Code Complete.

      The idea is to keep the code readable and maintainable with the least amount of re-invention of the wheel. With good coding practices, it's easier to avoid bugs in your own code and spot them in others (reviews are also a big plus on both counts). And it gets any religious battles out of the way up front, so you don't have to waste time bickering later on.

    12. Re:Comments by Webmoth · · Score: 5, Insightful

      Write your comments first, then code to match the comments. This way, you are forced to clearly define the input, output, variables and algorithms that will be used in the code BEFORE you start coding. When it's clear in your mind, the coding becomes easier and less confusing; and you have an outline to follow to make sure you don't forget something.

      If you write the code first, then annotate, you fall into two traps: "What the heck was that variable for?" forgetfulness, and "It works so stop messing with it" laziness.

      --
      Give me my freedom, and I'll take care of my own security, thank you.
    13. Re:Comments by Helios1182 · · Score: 2, Interesting

      If using Java, make sure they use Javadoc compatible comments for every class and method.

    14. Re:Comments by iabervon · · Score: 4, Funny

      I prefer:

      if x==456 then //checks to see if x is equal to 256. If it is, then the code within is executed

      That way, there's less chance for confusion if the code gets modified in the future.

    15. Re:Comments by BobearQSI · · Score: 4, Interesting

      There is lots more to coding standards than just comments and style. Where I work, portability and maintainence are of high concern too. Certain rules, like no hard-coded values such as 563, allow for much better code maintainence. Other rules, like in C/C++ never using an int for any value other than 0-127, and never using a char for anything other than text characters, allow for code portability. These are just some of the rules. If your product is designed for one environment, you may have different coding standards. In the past, we have gotten together as a software team and reviewed other standards found online and combined the likes and the like-nots to create our own, tailored for our industry and requirements.

      Style is good for readability and also for consistency. Requiring spaces before and after operators like = and + help in reading complex lines. Parens () help also. Setting requirements for function bracing (or what goes on a line, depending on the language), and tabbing help multiple programmers understand and easily see the program flow of others.

      Anyone who protests that they like their own style better because they can read it eaiser (while everyone else can't) shouldn't be working for you. Team players are needed. We've resolved many such arguments satisfactorily in the past by simply putting it to a vote. And those team players gracefully accepted the majority.

    16. Re:Comments by CausticPuppy · · Score: 5, Insightful

      Our coding standard is a little like this:
      Write clean code that can be easily understood by reading it. That is, good variable and function names, try not to make any absurdly complicated statements, and have your comments explain the logic of the operations. As for style, try to stick with the style that the original author started with. And finally, all people who use Hungarian notation are locked in the basement and given menial tasks until they repent their sinful ways


      Well that's a good start, with good intentions, but you need to have a standard definition of what constitutes good function names and good variable names. If you have 5 different programmers on a project, you'll have 5 different opinions on what good names are.

      Make sure your coding standards are DOCUMENTED.

      If it's a java project, the best source would be Sun's java coding standards. A very useful tool for this is Checkstyle. You can decide which rules to enforce (some of the ones enabled by default are more annoying than anything) but if you take the time to get your code to where Checkstyle likes it, you'd be amazed how easy it is for humans to read.

      As for my department, we use CVS for version control.
      Every time code is checked into CVS, it is formatted by Jalopy. So, it'll look nice and neat the next time it's checked out.
      Also, we have a script that does nightly builds, and then emails the result to everybody on the team. So if you checked in something that breaks the build, everybody knows about it the following morning. :-)

      We have a regular release schedule. All work is done on the main CVS branch, but when it's time for a code freeze, the new version is branched off and tagged in CVS. During QA testing, bugs are fixed in the branch and the mainline. New features are only added to the mainline.

      When we are ready to deploy, we tag the release in CVS. The deployment script checks the tag out of CVS, builds it, and packages everything up into the relevant .ear files which Operations can then take.

      This is all a very strict process, but things rarely fall through the cracks this way. If you don't have any processes in place now, it's best to implement them a step at a time. Get everybody used to working with CVS or some other version control, get them used to the notion of tagging and branching, and make sure there's actually a document detailing whatever processes you have.

      And lastly, have code reviews every week or two. Review a different person's code each time and make sure everybody on the team is allowed to have input. If you're not at the coding stage yet, have design reviews.

      --
      -CausticPuppy "Of all the people I know, you're certainly one of them." -Somebody I don't know
    17. Re:Comments by multipartmixed · · Score: 2, Funny

      Out of curiosity, what kind of platforms do you code for? Even my commodore 64 had 16-bit ints.

      --

      Do daemons dream of electric sleep()?
    18. Re:Comments by BrynM · · Score: 2, Insightful
      Write your comments first, then code to match the comments.
      This is why Design Documents are so important. For those sitting there thinking "// checks if x == y then proceeds" is a good comment, the rest of us call this "comment first" idea "planning". It has been working well for coding since the begining and has worked for other things for centuries if not millenia. The most frightening thing to think when handed old code is "My god! They never had more than a meeting of planning for this pile!" Bad or after the fact comments betray a lack of planning every time. Not commenting is almost a downright admission.

      When I see code like this, I have turned to my current boss/client and said "You didn't plan this thing very well at all did you?" on many occasions. That question always gets a look of guilt quicker than two teens with no clothes on when her dad walks in. When you explain how you noticed so quickly, you can see the look of "How did I get here? Do I know what I'm doing?" wash over their face a few times over as they think of everything else they are in charge of in the same light... and wonder if their mistakes are always that obvious to others. I remember one PHB wo implemented a "Code Review" the very next day. Fun! Sad, sadistic, pitiful fun - but still fun sometimes.

      I wish I had mod points for you Webmoth. You hit the nail on the head dead square. Even countersunk it a little.

      --
      US Democracy:The best person for the job (among These pre-selected choices...)
    19. Re:Comments by Anonymous Coward · · Score: 4, Insightful

      Don't do weekly code reviews. Instead, make it a checkin requirement: in order to check in any code, no matter how inconsequential, it has to be reviewed by at least one other dev who knows what the code is doing.
      Also, have a simple set of automated test scripts and require that every change must build and pass all of the scripts before being checked in. Also have a more in-depth set of test scripts that are run on a regular basis, and make sure that failures are fixed. Finally, make sure that you have a test org in charge of maintaining the scripts and adding new ones, so that your code doesn't become 'immune' to your tests.

    20. Re:Comments by Anonymous Coward · · Score: 4, Insightful

      I used to have that feeling about Hungarian too. Until i read Joel's view of how Hungarian is meant to be . There are definitely some times when it is a Good Thing. Not for your str_ThisIsString variables, but to put you in a mindset so that you know whats going on. Its not something to use everywhere (maybe 5-10% of your variables will need it), but if you put it where its needed, its something that definitely helps code maintainability.

    21. Re:Comments by GlassHeart · · Score: 3, Interesting
      Well that's a good start, with good intentions, but you need to have a standard definition of what constitutes good function names and good variable names. If you have 5 different programmers on a project, you'll have 5 different opinions on what good names are.

      So what if they are not all uniformly named? Has anybody actually seen a code base where it's possible to call a random function in a class without looking at documentation or the header file? As long as it's an informative name - and code reviews should flag bad ones - you should save your fight for something that actually matters.

      Guidelines on naming, on the other hand, is a great idea. Clubbing smart developers over the head for this is pointless.

      if you take the time to get your code to where Checkstyle likes it, you'd be amazed how easy it is for humans to read.

      One of the myths of software engineering, IMO, is that code is hard to read. For a competent programmer, code is *not* hard to read, in the sense that it's pretty easy to figure out what the code is doing. The problem is what the code is attempting to do, and possibly why. This is why brace styles, spaces versus tabs, and other "low level" coding standards do very little except to annoy. I've worked at several companies, each with different coding conventions, and I follow most of them. Unfortunately, I've found little relationship between maintainability and adherence to coding standards.

    22. Re:Comments by Tim+Browse · · Score: 2, Insightful
      Even for a novice programmer, code like if(x == 456) is self-explanatory, no comments are needed.

      You're right - how could it be possible not to know what that code is doing? (The rule is, the only magic numbers allowed are -1, 0, and 1. 456 is right out.)

      But then again, don't worry, everything should be clear, right? :)

    23. Re:Comments by drxenos · · Score: 2, Insightful

      0-127??? Why? The standard guarantees that int is at least 16 bits.

      --


      Anonymous Cowards suck.
    24. Re:Comments by Hognoxious · · Score: 3, Funny

      Er, like WHOOOSH or something.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    25. Re:Comments by swillden · · Score: 4, Funny
      if (x == 456) { // Check if step motor reached final position. If yes, halt motor, otherwise step

      That line still contains an example of one of my biggest pet peeves... the use of magic numbers. Okay, so the comment explains what 456 is, but not why and makes no provision for managing changes. What if a new design had a stepper motor whose final position was 256?

      Magic numbers are a reality, of course, especially when dealing with hardware. But if there's no way for the code to dynamically determine the values, the very least you can do is to define a symbolic constant, and collect the constant definitions together in one place. For example:

      #define FOUR_HUNDRED_FIFTY_SIX 456

      // ...

      if (x == FOUR_HUNDRED_FIFTY_SIX) { // Check if step motor reached final position

      See how much better that is? And if the value changed to, say 100, all you have to do is modify the constant definition in one place, like:

      #define FOUR_HUNDRED_FIFTY_SIX 100

      Really, a little extra work up front goes a long way.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    26. Re:Comments by Philodoxx · · Score: 4, Insightful

      It's important to comment "if x==456 then..." if it is not readily apparent why x might contain that value. having a comment of "// check to see if x is 456" is counter productive, you're right. A comment like "// x having the value of 456 indicates that the previous operation failed because the CPU burst into flames" is useful, and can help programmers decipher huge decision structures.

      --
      Oh, a lesson in history from Mr. I'm my own grandpa.
    27. Re:Comments by Simonetta · · Score: 2, Interesting

      Anyone who protests that they like their own style better because they can read it easier (while everyone else can't) shouldn't be working for you.

          Maybe instead these people can be requested to write programs that reformat the written code from their style to the company standard style. They should do this, of course, on their own time at home.

          No magic numbers in the code is a good idea. Especially for embedded systems code where there are lots of configuration registers in the microcontrollers to set up.
      For example, avoid constructions like:

          ldi config, 0x28 ; LoaD Immediate Value into register
      instead use:
          ldi config, (1 bit5goodname) | (1 bit3goodname)

          I'm always encouraging people on embedded coding sites to do this.

          Running the comments through a spell checker is a good idea. If you can get the language environment to separate the comments from the active code and feed the comments alone into a good spell checker. I haven't seen any compiler yet that does this, but it should be too hard to set up a text filter program for it. A least no one in your company will be embarrassed by simple misspelled words in the comments. Great for your H1-B people also who are using English as a second or third language and haven't mastered the unusual spelling of thousands of common English words.

          I'm also becoming a strong believer in Talking Documentation. Get a high quality Speech-To-Text converter program and a fast PC. Place this PC next to the development PC with the source code. Start the Sp-to-Tx and the source code listing. Describe in words the entire listing as if there were someone there who was endlessly fascinated by the code and you. Take hours if you need too. Save the text file of the transcribed dictated documentation with the source. Don't be concerned about formatting and paragraphs or even coherence. If needed, someone can do all that later. It's important just to have the detailed dictation text that describes the source. It seems strange, but it does work as a documentation technique.

          Don't forget to spell check your own stuff too.

    28. Re:Comments by NilObject · · Score: 5, Interesting

      The best advice I ever got was to write "why", not "what" a piece of code does.

      // Increment counter
      counter++;

      See? Completely useless. Let's try again:

      // We've processed one more message
      counter++;

      Ah, much better! Any Computer Science peon knows that "counter++" increments counter. What they might not know is why. Those simple bits of "why" comments can make reading code so much easier.

      Organizational comments (those that delineate what chunks of code inside of a method do) can be helpful, too. (Ex: "// Normalize string", "Encode string", "Send String") They make narrowing in on a particular "task" performed in a method even easier.

      Other than that, however, the biggest and most persistent and most annoying problem I have is poorly-engineered code. Some people just do not know how to apply their college degrees. I wish CS degrees had a bigger emphasis in software engineering. Would you hire an architect who couldn't design anything bigger than a porta-potty? Why does the CS industry get away with doing the same thing?

    29. Re:Comments by chachacha · · Score: 5, Insightful
      Agreed.

      People forget that code itself is a language. And usually a much more clear and logical one than English. Requirements docs are for explaining complex business processes and code itself explains most of what is going on. That is not to say that comments are not important, but when they exist I want them to be there for a reason. Anyone reading your code is assumed to be conversive, if not fluent in the code language, so comments should explain things such as:

      • strange idioms (ie. select((select(FH), $|++)[0]); // autoflush FH)
      • reasons for non-obvious choices of algorithms (ie. // we're not using an FFT here because ...)
      • intended input/output (a "comment preamble" to a method such as generated by VisualStudio. This is extremely useful for someone following a stack trace.)
      • candidates for refactoring (ie. // this method can now be collapsed/condensed ...)
      • pitfalls that are likely to trip up an intermediate developer
      • (many other valid reasons exist)


      Comments that merely "translate" basic code language into english are at the very least useless and often harmful: they bloat the filesize, obfuscate executable lines (I have deleted blocks of apparent comments only to find that unit tests are subsequently failing - the reason? - a single line of executable was buried between 2 dozen lines of commented out code), increase the burden on the maintainer and/or reader who must sort out the important details from the quotes laid down by Capt. Obvious.
      --
      I do like programming things that work super quickly, especially when they work super quickly, super quickly.
    30. Re:Comments by roystgnr · · Score: 5, Funny

      Even for a novice programmer, code like if(x == 456) is self-explanatory, no comments are needed.

      You're right - how could it be possible not to know what that code is doing? (The rule is, the only magic numbers allowed are -1, 0, and 1. 456 is right out.)


      Okay, but that's going to get really hard to debug!

      if (x == (1+1)*(1+1+1+1)*((1+1+1+1)*(1+1+1+1)*(1+1+1+1)-(1+ 1+1+1+1+1+1)))

    31. Re:Comments by shobadobs · · Score: 2, Insightful

      I've never understood all this hokery. You only have to obey one simple rule.

      The general theory of coding practices: Don't be a moron.

    32. Re:Comments by BrynM · · Score: 2, Insightful
      nonsense... planning ahead does not equal comments in your code... planning ahead, as you mentioned at first, can be in many forms, and hopefully takes place long before you open up your favorite text editor to write some code...
      If you have prelimary docs, then just open them in a text editor and cut-n-paste from them as you go. How hard is that? Don't tell me you're one of those who writes a design doc, only looks at it rarely and imagines "I remember it all" (I'm hoping you're not, you seem smarter than that). That's not planning, that's getting the general meetings out of the way then running away to code off the cuff.

      Referencing the documents that the PHB/customer helped write also makes your comments easier for them to understand. Not to mention something the PHB/customer is actually happy to look at (gasp!). It usually makes for better and more consistant documentation - especially if you add in minor "this is for that" line comments where needed.

      When it comes down to it, it's actually a lazier way to go in some respects even. It's been a huge time saver and a check against feature creep for me in many cases. Try it and you may never go back.

      --
      US Democracy:The best person for the job (among These pre-selected choices...)
    33. Re:Comments by th4tGuy() · · Score: 2, Insightful

      Agreed...

      And I would consider attempting to get in the habit of putting the number / constant first. If you accidently drop an = from ==, it will be a compiler error. The other way around can be maddening to hunt down and correct... although a good IDE will at least give you a warning.
      EX:

      #define UPPER_BOUND 456

      if(x == UPPER_BOUND) do_something_useful();
      if(x = UPPER_BOUND) assign_upper_bound_to_x(); and_always_evaluate_to_true();

      if(UPPER_BOUND = x) compiler_error(); //!

      --
      -- As soon as I have an interesting sig, you'll be among the first to know!
    34. Re:Comments by lourensc · · Score: 3, Insightful

      if (x == 456)
      {
      ...;
      }
      this is bad code and no amount of commenting is going to fix it. It begs 2 questions; What is x and why 465? I would recode it as something like this that makes the purpose clear enough that no comments are needed:

      const int screenWidth = 456;

      if(xCoordinate == screenWidth)
      {
      ...;
      }

      this way I type more code but less comments.

    35. Re:Comments by shinghei · · Score: 3, Informative

      But the generated document is only as good as the comment itself, isn't it? Correct me if I am wrong, I don't think any of the tools that you mentioned can generate any intelligent comment. What good is the comment "The openSocket method throws a SocketException"?

    36. Re:Comments by weicco · · Score: 4, Funny

      Oh yes, comments. Well we use comments as version/history information. We have every code file and project file on a single samba-shared volume. When somebody wants to change something he/she shouts "I'M OPENING THE FILE X, DON'T TOUCH IT NOW" and he/she has done modifications he/she adds very informative comment somewhere in the file (name/date/what was done), saves file back to disk and yells "OK, FILE X IS FREE NOW"

      Documents... There is no documents. Who needs those anyways? It's much more fun to code something when you really don't have any idea what its supposed to do.

      Test plans? Nah, waste of time I say!

      Testing? Well, somebody runs it and if it doesn't crash, it works.

      I must say I'm in the best damn work place ever! And now if you please, I'll go and find some ethernet cabel to strangle myself.

      --
      You don't know what you don't know.
    37. Re:Comments by zardo · · Score: 2, Insightful
      It's called test driven development, some people do it without even thinking about it, everyone else is a bad programmer. By documenting your thought process, you help other programmers mature. That's the jist of it.

      In addition to everything others have mentioned, for web development you need a good deployment system to compliment subversion or CVS or whatever you use for version control. As far as planning goes, always start with the data model, that is my best advise. Come up with the most versatile data model you can, try to plan for everything, don't just add columns to your existing tables as you go along (or try not to at least). Using a program like inkscape, omnigraffle, or visio can be handy for this, although it takes a bit of practice to come up with useful diagrams.

      Usually the data model is the easiest part of the application to convey visually and will lead to the quickest understanding by newcomers. It's usually the first thing I start with when I'm familiarizing myself with something new, whether or not there is good documentation, I'll look in the database first.

    38. Re:Comments by chachacha · · Score: 4, Interesting
      But even that can be rewritten as
      const int SCREEN_WIDTH = 456;
      if (SCREEN_WIDTH == xCoordinate) { ...
      Using the constant on the left hand side of an equality test such as this will cause a compile-time error if you accidentally type
      const int SCREEN_WIDTH = 456;
      if (SCREEN_WIDTH = xCoordinate) { ...
      Come on, we've all done it. ;)
      --
      I do like programming things that work super quickly, especially when they work super quickly, super quickly.
    39. Re:Comments by JulesLt · · Score: 3, Informative

      Which is why we would say :
      1) Don't use variable names like x, use something that indicates the meaning of the variable - so maybe in this case lErrorStatus
      2) Don't hardcode magic values, use a meaningful constant - which also means only one point in code needs to be changed if we switch CPU and find there is a different on-fire code

      Then we get

      if lErrorStatus == CPU_ON_FIRE then

      Which I think is pretty self-explanatory.

      One thing that isn't clear yet is whether this bit of code is sitting in a little function or part of a big block - i.e. what it's going to do on the 'then'.
      Now at some future point we might find ourselves needing to check CPU_GETTING_QUITE_HOT. So we will still have to impact all occurrences of
      lErrorStatus == CPU_ON_FIRE to add an extra test.
      This leads to

      3) Encapsulate tests in meaningfully named BOOLEAN functions.

      I'd say it is swings and roundabouts as to whether (3) is worth the effort.

      If the _cpu_on_fire(ErrorStatus) test is just done once, then we've had to go to a lot of effort to encapsulate a single line of code (as the expression is already boolean). If it is used >1 times it is definitely worth wrapping, ditto if the expression is complex - just to make sure developers get into the habit, as much as to protect against any change. (I think it's better to get into a slightly more time-consuming habit of doing the right thing and break it occasionally, than into the habit of doing the quickest thing and having to think to do the right thing).

      The other principle that points to (3) is the one that blocks of code should be 'readable' and if possible a block should fit on one page - i.e. when you have an
      if . . then . . .else . . end structure and the bodies of all the elements are large then each should be a procedure/method itself.
      Again, _cpu_on_fire(ErrorStatus) isn't a good example as we'd be replacing one line with one line.

      However, if you have a standard logging mechanism (say log4j), and template code for functions/methods, you can use this encapsulation to record the fact that the test occurred, input and output values, rather than leaving it to the individual developer to remember to add logging before their 'if' and on each conditional path.

      --
      'Capitalists of the world, unite! Oh ... you have' (League Against Tedium)
    40. Re:Comments by fgb · · Score: 3, Insightful

      I get really irritated when developers check in code with sections commented out. If the code is no longer relevant - delete it! If you really need to get it back, get it from a previous version in the source control system.

    41. Re:Comments by slackbits · · Score: 2, Insightful

      >Using the constant on the left hand side of an equality test such as
      >this will cause a compile-time error if you accidentally type
      >const int SCREEN_WIDTH = 456;
      >if (SCREEN_WIDTH = xCoordinate) { ...

      It depends on the language. Any language that has a boolean type is going to give a compile time error to xCoordinate = SCREEN_WIDTH. The only time it will not is if you write if (something = true). But then again that comes down to bad code.

    42. Re:Comments by arkanes · · Score: 2, Insightful
      None of the above, because you're likely to be using these sorts of checks a lot of times, in multiple places. Write functions (make them inline or macros if performance is what freaks you out) with descriptive names that perform these checks.
      if (name.FitsInBuffer() && name.length > 0)
      for example. Of course, in this particular case it'd be better to move the maxLength checks into whatever class name is and throw exceptions. These kind of long repetetive checks are prime breeding ground for typos and brainfarts that introduce rare bugs, because the repetetive nature of the code makes your eyes skip over small inconsistencies.
      if(Fark.length < maxNameLength) && (Fark.length > 0)
      (repeat 10 lines checking different variables)
      (Logo.length < minNameLength) && (Logo.length > 0)){
    43. Re:Comments by Ors · · Score: 2, Funny

      The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change.

      -- FORTRAN manual for Xerox Computers

    44. Re:Comments by Boing · · Score: 2, Insightful

      I agree with you, even inasfar as to say that I think putting constants on the left side is a good habit. However, there is a hit to readability when you do it that way. English speakers read left-to-right, and the subject nearly always precedes the object in a sentence. "if (5 == x)" may keep you from doing accidental assignments, but it also reads the same way "red is my car" would. For me, that means another second or two of parsing it in my head, which breaks the flow of my code review.

    45. Re:Comments by maxwell+demon · · Score: 2, Interesting

      Why do you consider indenting by 2 spaces as stupidity?
      And how can the result of this rule be that developers use tabs?

      --
      The Tao of math: The numbers you can count are not the real numbers.
  2. Joel on Software by Marxist+Hacker+42 · · Score: 4, Informative

    Has several excellent articles on the subject This is about as good of a starting place as any.

    --
    SJW: a person who perceives an injustice, and while correcting it, commits a greater injustice.
    1. Re:Joel on Software by ajdavis · · Score: 5, Interesting

      Yeah, but Joel's an ass. Have any of his worshippers here on /. actually *used* something written by Fog Creek or whatever? FogBUGZ, a web-based bugtracker, seems to be his one claim to fame, & it's terribly mediocre. I mean, mostly it works, but the search function doesn't, the UI is inconsistent, & while you can define filters (such as, "my open priority-1 bugs"), you can't share them, which makes them nearly useless. Joel writes a good spiel, but when it comes to coding, his company ain't the shit.

      Plus, he argues passionately for paying programmers well & giving them exciting projects, but in at least two cases he hired interns to start his company's most interesting apps.

      Dude needs to work on his street cred.

    2. Re:Joel on Software by measterbrook · · Score: 2, Insightful

      > Plus, he argues passionately for paying programmers well & giving them exciting projects, but in at least two cases he hired interns to start his company's most interesting apps.

      That is because Joel has fallen into the legacy vs new trap.
      Legacy code is difficult to maintain and only your best and most experienced programmers can work on it without either braking it, making it worse, or doing it very very slow. In comparison, writing new code _seems_ relativily easy (can you hear the alarm bells?).

      So if you have to put your best programmers on the legacy code, everyone else gets to write the new code ... badly (but you don't realise this until maintanance time). The new code becomes legacy code, which requires your best programmers, which leaves the rest for the new new code. And the cycle continues.

      There is no easy answer, pair programming helps, but requires more staff. Not many managers understand the "pay a bit more now, collect the big reward later" way this works. Good experienced programmers are expensive, young inexperienced progammers are cheap if you only consider how much you pay them (and not how much you have to pay to sort out the mess later using your expensive experienced programmers).

      It works for me - I make a living out of fixing bad legacy code. I don't get to work on the sexy new projects, the youngsters do, creating my future employment needs... and so the cycle continues...

  3. Help people play to their strengths etc.... by FyRE666 · · Score: 4, Interesting

    If you really are starting from ground zero, I'd suggest setting up a repository such as SVN as a good first step. Couple this with a good template to set up standard locations for documentation directories alongside the code trunk and branches (and any other resources your projects requires (images, sound other media). Make sure everyone uses the repo - even if you have to spend a day leading people through it - you'll save time later. This also ensures your projects are backed up (so long as everyone checks in at the end of the day at least), and screwups - such as deleting the wrong directories and forgetting about it for weeks can be reversed.

    Obviously there are other issues such as naming conventions, useful comments etc, which are often neglected in small projects, but become more important as more people work together without wars breaking out!

    Find out your teams individual strengths and preferences - there's no point trying to hammer everyone into the same mould - some people will naturally gravitate toward, and excel at certain tasks. It's important for efficiency and general happiness that this is taken into account when allocating resources to a project.

  4. Evolutionary Prototyping by PIPBoy3000 · · Score: 4, Insightful

    In my job as a web developer in a healthcare system, I'm all about evolutionary prototyping and other interative methods. There's a handful of big projects where we take a more traditional waterfall approach, but even then it's highly modified.

    It's nearly impossible for me to get final specifications from a user until they've actually seen something. Paper is okay in a pinch, but a semi-functioning web application is worth a thousand meetings.

    1. Re:Evolutionary Prototyping by ScentCone · · Score: 3, Interesting

      It's nearly impossible for me to get final specifications from a user until they've actually seen something. Paper is okay in a pinch, but a semi-functioning web application is worth a thousand meetings.

      What's amazing is that you can say that in two sentences, and most web developers here will completely get what you mean... and that traditional managers (of developers) will get incredible hives and seriously rethink your annual bonus for uttering such heresy.

      My favorite flavor of Not Getting This are the managers or customers that want you to mock up some screen shots for discussion, and are happy to pay for you to do so in Visio, or a paint program, etc... but if you instead actually whip together some HTML-based forms (much of which can eventually go towards further prototyping or actual use), you've opened the door to arguments over charges for having "jumped the gun" on the programming cycle. Never mind that I can produce conceptual mockups that actually render on a browser faster than by most any other means. But since a cheesy little pull-down-generating server-side script is "programming," there's PHB-fodder about having already done dev work before all of the requirements are described. Oh well. I'd rather write off a chunk of the project's proceeds than try to hammer out all of the requirements on paper first. In real life, with projects that must go from "I saw this thing when I checked out at Amazon" to being functionally bolted onto an existing web presence in a matter of a dozen man-hours, that's frequently impossible.

      --
      Don't disappoint your bird dog. Go to the range.
    2. Re:Evolutionary Prototyping by open_source_dweeb · · Score: 2, Insightful

      But since a cheesy little pull-down-generating server-side script is "programming," there's PHB-fodder about having already done dev work before all of the requirements are described.

      The flip side of this is that after showing marketing a semi-functional prototype that is pretty close to what they are looking for, there is often a tendency to assume that the project is near the code-complete phase and that a majority of the resources can be reallocated elsewhere. Just leave a couple of developers on the project to polish up the code and the installation program ... then ship it!

      Because of this, I usually like to leave an obvious (from the UI perspective) piece of functionality missing from the functional prototypes. This makes it clear to the management and marketing types that there is more work to be done. They don't really care that the prototype is non-scalable and has the web server making direct database calls, whereas the real implementation would need the web server going through middle-tier business components, data access layers, etc.

  5. My boss doesn't care by b0lt · · Score: 3, Funny

    I like to think of it as "don't ask, don't tell" :D

    --
    got sig?
    1. Re:My boss doesn't care by dubl-u · · Score: 2, Insightful

      And the original poster should consider the benefits of something nearly that loose.

      Don't arbitrarily set up standards. Ask people what problems they have. Tell people what problems you're facing (e.g., you need to be able to move people more easily between projects). Then ask the developers who don't have those problems what they do. Feel free to toss in your own suggestions, too. But let them talk first. And let the developers decide how to do the work as long as they address your needs.

      Remember that you're not working in some Taylorist 1930s factory where you have to specify every motion. Creative work, which is what your developers are doing, is utterly different than factory work. (See the book Artful Making for more info on that.) Treat them like professionals and they'll act like professionals.

  6. Unrealistic expectations by TheNarrator · · Score: 3, Insightful
    Right now I'm more concerned about trying to set up coding standards, so that any developer can jump into any part of a project and be able to figure out what's going on, without wasting a couple hours just to figure out the code.


    Unless you are dealing with trivial projects it will take more than a couple of hours to figure out the code. Even the best documented open source and commercial projects take a few days to figure out.

  7. GOOD code review; Chief Designer at every inspecti by mekkab · · Score: 4, Insightful

    At every inspection; and of course example code for everyone to mimic the coding style.

    And good unit test drivers.

    Awesome commentary (both at the top of a package outlining the entire low-level design and at the algorithm level) goes without saying.

    Oh yeah, and run spell on your code. I mean, really!

    --
    In the future, I would want to not be isolated from my friends in the Space Station.
  8. Looking for magic? by YrWrstNtmr · · Score: 4, Insightful
    Right now I'm more concerned about trying to set up coding standards, so that any developer can jump into any part of a project and be able to figure out what's going on, without wasting a couple hours just to figure out the code.

    That is a pipedream. Any project of significant size will require some immersion before a new proj member can get his hands around the particular bit he's trying code/solve.

    Standards can be good, but they're not magical. Unless you're trying to generate a group of little robots, everyone has a slightly different style.

    1. Re:Looking for magic? by waldomaniac · · Score: 2, Insightful
      Good call. Waste a couple of hours?... How many hours are you going to want to spend on the standardization process? And enforcing it? Beware the tools of micro-management... standardization, time-keeping, the dark side are these... Personally, I'm down with the tagline I saw one time:
      Comments should be banned - it was hard to write, it should be hard to understand.
  9. A Good Coffee Break by JoeShmoe950 · · Score: 2, Interesting

    This doesn't directly answer the question, but a nice big break in the middle of the day helps me get myself on track easily. After a few hours of coding, I may start to slow down. If I just take an hour (eat lunch, walk around a little), my brain clears, and I come back fully productive. My work place allows this, and I'm not sure how many others do.

    1. Re:A Good Coffee Break by Eberlin · · Score: 2, Insightful

      A good break in general will clear the mind often enough to get unstuck on some problem. Coffee is optional. I often find that walking around (even just in the room) with a stress-ball, and talking aloud to myself will reveal solutions that wouldn't have otherwise shown up if I were buried too deep in the code.

      That and something to scribble on. Either lots of paper or a whiteboard. Whiteboards are cool for getting your thoughts organized. Unfortunately you can't make printouts afterwards...but a good digital camera snapshot of a whiteboard will give you enough to remind you of what you thought up.

      The general hint -- give yourself some time to step back from the problem. There are times when it's good to bury yourself in the code and times when it's better to think things through away from the code.

  10. Standardize on a good language. by Anonymous Coward · · Score: 2, Funny

    The importance of a single language standard can't be overstated. Ever since my company switched to LOGO I can understand my co-workers' code at a glance.

  11. GOOMOALMWIP/GOOMCALMWIP by Martin+Blank · · Score: 2, Insightful

    Get Out Of My Office And Let Me Work In Peace

    or

    Get Out Of My Cubicle And Let Me Work In Peace

    This applies mostly to the people that come in and have to inform me of their new cat, girlfriend, boyfriend, computer, game, TV, kitchen, car, shoes, and/or midlife crisis (and that's just the top of the list).

    A request on the part of the devs under your control: Don't implement a new paradigm every time one comes out. From extreme programming to agile programming, from scrums to design workshops, find something that works in your particular case and stick to it. Your employees will thank you for it (at least in the long run by not planning your demise in the parking lot after the fifth methodology change that quarter).

    --
    You can never go home again... but I guess you can shop there.
  12. Works for some companies not others. by jellomizer · · Score: 2, Interesting

    First language try to choose languages that work well on multiple platforms with at most a recompile. Languages like PHP, Python, Ruby, are Good. If you have to use .NET try to make your programs compatible with Mono. Even if you are using a Windows network and don't plan to switch anytime soon working with platform independent language give you the ability to better negotiate with MS for licensing price because your 3rd party apps will cheaply move over to the new platform. Also programs designed to be platform independent tend to migrate a lot easier to new versions of the OS. Avoid using and single platform library or other 3rd partly libraries unless you really need them. If they stop development you could be stuck.

    Second have a Good Data Warehouse try to use Rational Database servers that support Stored Procedures and Triggers, which is dependable. MySQL 5, PostGreSQL, MSSQL, Oracle are all good choices. I would put money to give all the DataBase Servers some good specs and conversly I would put all the data manipulation into Stored Procedures and Stored Functions. Also when creating them give them a prefix to show that they are your companies specialized functions and not built in the Database Server. The Database should give you the data they way that is most convenient for you to use. The reasoning for this is that it normally reduce network traffic to the SQL Server, and allow porting applications to different languages and platforms easier because the data format part is still complete.

    Third use have all your apps on your intranet be web based. first it eases deployment and also allows desktops to be upgraded without killing the app every security patch.

    So if you make a all your Apps Web Based with the bulk of the calculations on the Database server and having the Web Language handle the User Interface, and depending on you size of you apps a 3 or 4th tear with custom libraries for standardized uses of Interface and data a.

    --
    If something is so important that you feel the need to post it on the internet... It probably isn't that important.
  13. Our style! by Doug+Tanner · · Score: 2, Informative

    I work for one of Activision's subsidiaries and this is what we use:

    int* gpiGlobalInt;

    int FunClass::GetSize(int _iArg1, bool _bArg2)
    {
        bool bBool;
        float* pfFloat;
        static int siStaticInt;

        for(;;)
        {
        }
    }

    Seems to work out well enough.

  14. WHAT Standards? by thepropain · · Score: 3, Funny

    I'm all self-taught, so I have my own style which others tell me is impossible to make heads or tails of. The standard is: the boss promises stuff to our clients, and I have to whip it out [snicker] as fast as possible. Doesn't leave much time to make easy on those who would come after me. I jokingly call the mess of code I have to make JOB SECURITY.

    --
    "You know you're narcissistic when you quote yourself in your sigs." -- PRoPAiN!
  15. Coding Practices by Billosaur · · Score: 5, Insightful
    Here a just a few things that come to mind:
    1. Version Control - find a VC system everyone can agree and use it religiously, whether for scripts, programs, or even web docs. I've use CVS mainly, with a little Perforce, and Subversion is good so I hear.
    2. Coding Standards - depending on how many and what type of languages you have, you'll want to develop standards for how code will be laid out and documented that will make sense and also make it easy for somebody to move from one code base to another with as little trouble as possible. You can be as detailed as like, right down to conventions for naming subroutines and indentation, but don't get carried away or you'll stifle creativity.
    3. Documentation - not just documenting code (which any programmer should be doing reflexively), but documenting system flows and procedures. It doesn't hurt to throw together text docs on your more important scripts/programs, outlining where they live, how they're run, etc.
    4. The Brain Book - there's nothing I hate more than starting a new job and having to learn all those server names, IP addresses, what I'm supposed to have access to, where in the directory tree the stuff I works on live, what types of DBs we use and their versions, etc. So I developed the Brain Book, where I would write these things down as I learned them, to have a point of reference. It's a good idea to do this for all your major projects, so as new people come on, they can spend less time learning their way around and more time coding.
    5. Code Review - everybody's coding style is different and sometimes they don't mesh well or there are divergent opinions on how a particular task should be coded out. Get your programmers together in a room and hash things out as a group. It will provide everyone with a say and may open up some people's eyes to new ways of doing things.
    --
    GetOuttaMySpace - The Anti-Social Network
  16. Specs, reviews & tools are the real key by VisualVoice · · Score: 2, Insightful

    From my experience managing many multi-million line code projects for many years, its the tools (source control, bug system, langauges) and a standard documentation templates (market requirements doc, product requirements doc and detailed design document, unit test document) that are more important to standardize than coding guidlines. Sure everyone should follow a good variable naming convention (hungarian or equivalent) and heavily comment each function's purpose, but beyond that you can waste a lot of team time on arguing about idententation, and micro-commenting guidelines.

    Also key is a standard process of developer peer reviews. All developers should have peers review specs. New or mediocre developers should have their code peer reviewed. Proven developers can be excused the code review but not the spec review.

  17. Project Management by LoaTao · · Score: 2, Informative

    You seem to be asking more about the basics of Project Management than specific tools. For a fair overview of the subject try this in Wikipedia. The grand-daddy of Project Management for software development is SEI-CMM.

    --
    The smartest man in the whole, wide world really don't know that much. - Mose Allison
  18. Experience counts by canuck57 · · Score: 3, Insightful

    My suggestion is get someone who has done this in a structured and successful environment. Otherwise developers will roll you over and your projects will be late, over budget and buggy.

    I have seen it so many times where an internal inexperienced person jumps in the saddle without mentorship and guidance in the areas of software development (NT or UNIX) and systems management not native to the environment. And I have seen how long companies suffer with the problems created by this and how much it costs companies in the end. It makes a $1000 per hour consultant look cheap.

    A good example is code management. Very few IT shops have it. Why? No one wants to know who checked in the buggy code! But few developers want such tools, especially the microwave generation. But at least when your caffeine isn't good enough and they move on you will know where the source code is.

    Sounds simple? Not really, there are hundreds of issues like the one above. And it can't be taught quickly.

    So get a consultant for 6 to 12 months that has done this, listen and learn and you will be off to a fast start.

  19. code complete has some good things to say by blackcoot · · Score: 5, Informative

    on this particular subject. i believe code complete 2 came out "reasonably recently". that said, were this my task, i'd say the following:

    1) document things thoroughly using a tool like doxygen. there is no excuse for interfaces not to be thoroughly documented
    2) adopt a standard naming convention. in java, this is easy -- just use the default. in other languages, you'll probably have to make your own up.
    3) pick an indentation style. it really doesn't matter which since tools like indent can convert between them almost painlessly. all code that goes into the repository is run through indent to put it into a standard format
    4) require that code compile cleanly with no warnings at the most anal retentive compiler settings before it can be checked in unless there are good reasons to ignore the compiler warnings
    5) average devs are only able to commit to the "head" fork (or equivalent in your sccs). the code is not committed to the "real" fork until it passes whatever tests you have
    6) incorporate tools like valgrind into your testing cycle --- they should come back largely clean. if they don't, things need to be fixed unless there's a really good reason not to.
    7) people who check in code which breaks cvs or, upon a code review, are found to not sufficiently adhere to your guidelines owe their dev group donuts.

    1. Re:code complete has some good things to say by masklinn · · Score: 2, Insightful
      3) pick an indentation style. it really doesn't matter which since tools like indent can convert between them almost painlessly. all code that goes into the repository is run through indent to put it into a standard format 4) require that code compile cleanly with no warnings at the most anal retentive compiler settings before it can be checked in unless there are good reasons to ignore the compiler warnings 5) average devs are only able to commit to the "head" fork (or equivalent in your sccs). the code is not committed to the "real" fork until it passes whatever tests you have

      5 is not that required since most modern version control tools are able to run scripts on your data before/after the commits.

      In that case, the indentation cleaning, compile test and full unit-testing of the modified application could be done automagically at commit, with commit refused if code doesn't seamlessly compile or if any unit test fails (any code change would also, naturally, require the concurrent commit of the modified unit tests for the code).

      --
      "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
  20. Standards by shoemakc · · Score: 3, Funny

    Yeah, standards are great.....we've got lots of them :-)

    -Chris

    --
    --an unbreakable toy is useful for breaking other toys--
  21. Programming Standards by clockwise_music · · Score: 5, Insightful
    In no particular order:

    1. Get a development database, a testing database and production database. Yes, you need all three.

    2. Write a few docs explaining each system. Make these are detailed as you possibly can. (This will save you weeks in the long term)

    3. Use software revision control. CVS, VSS, whatever, use one.

    4. Use a bug tracker. BugZilla, Jira, CityDesk, whatever, use one.

    5. Use whatever coding standards the language reckons you should. If java, use sun's standards. If microsoft, use their standards.

    6. Write automated unit tests. I don't care if you're not an agile or XP developer, write unit tests. Check out Junit, or Nunit, or just write your own.

    7. Setup some code so that you can check out ALL code from the source code repository and compile it by ONE COMMAND. Eg, "make" or "ant" or "maven" or whatever. This will take time but is worth it.

    8. Have a naming standard for database tables. This will make your life SOOOO much easier.

    9. Read thedailywtf.com and don't do anything that is posted there.

    10. Write specs for your new developers. Please write specs for your new developers. Don't just say to them 'fix this up'.

    11. Make sure code isn't hard-coded to a particular directory. Everyone does this. Fix it. (Might be part of step 7)

    12. Create your own standard config files.

    13. Have code reviewed by peers. Don't be a bastard but be nice when picking on people's code.

    14. As mentioned, comment your code but use the language standard. Java - javadocs, Perl - perldocs, etc. These are cool, but don't get too carried away. Nothing can replace a good spec.

    15. Ignore what most people say on Slashdot. (Except for me, of course).

    That'll keep you busy for a couple of months! Doing thiswill make you well on the way to having a pretty high level of coding quality. Most companies don't do all of them. Good luck.
    1. Re:Programming Standards by RetroGeek · · Score: 4, Interesting

      1.a Get a test application server and production application server. Yes, you need both. The development server would be the developers workstation.
      6.a Formalize the testing process by people other than the original developers.
      6.b Write test cases.
      6.c Do regression testing. Especially for "transperant to the user" changes.
      8.a Have a naming standard for table columns. This will make your life SOOOO much easier.
      11.a Where you do need hardcoded directories, externalize the locations in configuration files.

      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    2. Re:Programming Standards by NemoX · · Score: 2, Interesting

      Great post. Some additions...

      1. Use a code reviewer like FxCop for .NET stuff. You can build custom rules that your team decides on, and apply them to each program.

      2. Automate as much as possible with things like Ant or NAnt. The less people do, the less room for errors or discrepancies from project to project.

      3. Use something like Cruise Control .NET which will tie everything together, run coverage reports, automate builds, etc.

      4. Make a Utility library so that they have a common place to get repetative processes. (e.g. we have one that validates whether a number and address is a valid store for our company; it is used in 75% of our programs, but only coded once.) You could incorporate some common error handling like log4net or log4j into the utility.

    3. Re:Programming Standards by Tim+Browse · · Score: 2, Interesting

      Something else I've found useful (which I think I got from a McConnell or Maguire book) is the idea of priorities in your coding, which should be part of your coding standards. That is, take a set of features/aspects of code like this:

      • CPU Efficiency
      • Memory/storage Efficiency
      • Maintainability
      • Portability
      • Correctness
      • Testability
      • Robustness
      • etc.

      ...and then put them in order of priority for each project you work on. The order will vary depending on the project, but a lot of coders will program with the same priority list in mind no matter what they are working on (e.g. obsessing about efficiency above all else) unless you actually tell them what the priorities should be.

      Making the list and putting it in order just puts it on everyone's radar. I have at times had the list taped to the edge of my screen, so when I come up against a design decision, I check the list for guidance.

    4. Re:Programming Standards by swthomas55 · · Score: 2, Interesting

      Amen!

      In 30+ years of coding, I've used many different "standards". I've come to the realization that the details of the standard are unimportant -- what's important is that you have one.

      Personally, I find "hungarian" variable names painful to behold. But if I'm working on code that used them originally, I'll try to make myself be consistent with the existing style.

      Indenting and white space standards are totally unimportant with a good IDE. In Eclipse, hit control-shift-f to make it look the way you want it to.

      Commenting is more problematic. I've gone from heavily commented to no-comment XP programming. I've settled down into a "minimal comment" regime. I try to write code that doesn't need comments by using short functions with meaningful variable, method, and class names. But where a comment can inject additional clarity, or where the code is necessarily obscure, then a comment can really help. (And by obscure, I don't mean "obfusticated" -- I mean code that is handling some bizarre real-world circumstance that most code readers probably would not think of.) Use your judgement. Ask yourself "if I came back to this code in a year, what bits would I be confused about." Then clarify that code. If it can't be further clarified, write a comment.

      As for "javadoc" or "pod", I think that it is essential if you're writing code that will be used in "binary" form by others. Try using something like DOM or Spring without documentation and see how far you get! But Javadoc for the sake of meeting some metric ("all public methods must have Javadoc") is purely silly. Even when I was working on a strict XP team that enforced a "no comments" discipline, we put Javadoc on a couple of methods. We found ourselves continually going back to read the code to answer questions such as "is this index 0-based or 1-based?" A simple Javadoc comment stating "index is 1-based" saved many minutes of coding time.

      Practice test-first writing. It's weird the first several times you do it, but at least for me, the more I do it, the more comfortable it feels. You can't always do it, I'll be the first to admit. But if I never write a line of code that doesn't have a test motivating it, I have a lot more confidence that the resulting code is going to do what I intend it to do. On the flip side, if I can't think of a test case that requires some particular "if branch", then maybe I don't really need to write that line of code.

      Get a coverage tool and use it. Don't blindly try for ~100% coverage (you'll never get it anyway), but it can point out bits of code that are undertested.

      In addition to "writing specs for new developers", pair a new developer with an experienced developer for a few weeks. Just a couple of hours a day will transfer the group practices much faster than any document will. IMO, this works best when the experienced developer is the "navigator" and the new developer has his or her hands on the keyboard, "driving." Doing == Learning. Watching == Boredom and Distraction. As an experienced developer, this is really hard for me -- I want to drive -- but it really does work.

      Practice group ownership of code. Don't let any individual piece of code belong to a single person -- in the sense that only one person understands it and only one person is "allowed" to touch it. Not only can this save you when the "guru" leaves, but it helps to prevent wheel-reinvention and accretion of "ugly code". It encourages the attitude of "if it's broken, and I'm working on it now, then it's my responsibility to fix it."

      Frequent integration in a multi-developer shop is essential. Don't let each developer work alone for a month or maybe even a week without reintegrating the code.

      A bunch of this sounds very XP-ish. That's because XP is not a new thing. XP is a combination of good practices all "turned up to 11." We tried XP for about a year and had mixed results -- out of 4 projects, one was successful, one was an utter and complete failure, one was mothballed

  22. Doxygen by segfault7375 · · Score: 2, Informative

    One word.. doxygen. I had been working on a program by myself for a few years and was really the only one who knew the guts of it. We got a new person on it so I could move on to other things, and rather than spending a week or two showing her what she needed to know, I spent a few days adding doxygen comments to the project, and she was able to read the generated documentation for herself and picked it up in no time. It plugs in to Visual Studio very nicely if you use that, and if not, you can easily write a batch file to update your documentation. I just can't say enough good things about this tool. If you can get your developers in the habit of documenting in the doxygen format, your documentation will basically write itself.

    Segfault

  23. We don't need no coding standards! by MythoBeast · · Score: 2, Informative
    Ok, so the subject is misleading. As a C++ contractor with about 15 years of experience in a broad variety of shops, I've been exposed to quite a lot of different coding standards, from severely strict where they told me where and when I can use the spacebar, to the completely non-existent. Of all of them, I have found the GNU coding standards to be the best balance between the flexible and the legible.

    A few other details that I'd like to add. K&R braces were invented, not by K&R but by the guys who typeset their book. It is a severe roadbump to try and read code where the braces are at the end of an if statement instead of vertically alligned.

    Try spinal alignment for variables. Most people align their variables like this:


    int something;
    void somethingelse;
    longobjectname theThirdThing;

    Those with more of a clue align them so that you can find the variable name easily in a mess of them:

    int something;
    void *somethingelse;
    longobjectname theThirdThing;

    This puts some major space in some cases between names and short type declarations. Try aligning them like this:

    ...........int..something;
    ..........void.*some thingElse;
    longobjectname..theThirdThing;



    The problem with this technique is that, if you ever post your code on Slashdot, you'll have to replace spaces with dots and spend fifteen minutes trying to get it to render correctly because SD doesn't support a simple PRE tag.

    Other tidbits that have helped. camelNotation rules. Don't use hungarian notation, it doesn't work in a severely object oriented enviornment. Instead, preceed your variables with a single letter that tells you where it's declared. l for local, m for member (of a class or struct), g for global, that kind of thing. I've seen "my" used for member and "the" used for static very effectively, also, but stick to one.

    Most of all, good luck. Remember that a lot of people's beliefs in this matter have no foundation except for what they've been doing for years. I have faith in my standards simply because I've seen what happens when you don't follow them, and that's mostly confusion.

    --
    Wake up - the future is arriving faster than you think.
  24. That's Like Scrum... by Greyfox · · Score: 2, Insightful
    Scrum and Code Reviews are all well and good but people who've never done that before don't know what to expect, so they tend to be all over the place with their comments. This leads to code reviews where your code is nitpicked over every little thing and scrum meetings that grow and grow until they take 2 hours out of every day to complete. Neither of these things are beneficial to productivity.

    I find that a good standard for code reviews is to assume that the programmer knows what he's doing and I don't try to push my political agenda in them. If you want to have a passionate argument about hungarian notation or putting braces around if statements that only execute a single line of code, the code review is not the place to do so. If you think a data structure he used isn't up to the volume of data you'll be running through the system, THAT's something to bring up in the code review.

    You can require comments in your code all you want, but I find that you inevitably get something like this: "a++; /* Add 1 to a */" With no indication anywhere of what A is or why you would be incrementing it there. I would propose power stapling the offending programmers in such cases, until they learn not to do that anymore. I would say remedial English classes, but even I am not THAT sadistic.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

  25. Peer Review Often by ear1grey · · Score: 2, Insightful

    Establish regular peer reviews: regular, as in daily; and not just when the library is finished and ready for delivery.

    Peer reviews encourage developers to describe what they're doing and why they're doing it (not just conceptually, but at the code level) so deeper awareness of whole systems is fostered.

    This can lead to projects with less redundancy, and greater integration. It also helps ensure that code will pass any human driven acceptance tests that the commisioning agent may stipulate.

    An additional benefit is that utilisation estimates are improved because as developers get better at describing what they're doing, they become better at describing what they plan/need to do.

    The canny manager will schedule the peer-review session 30 mins before lunch, recognizing that it gives developers something to discuss as a group whilst eating.

  26. Worry about what not to do, too by Rocketboy · · Score: 5, Insightful
    Many (many) moons ago I worked for an IT manager who's explicit instruction was, "don't use arrays." He didn't understand them and, therefore, they were bad.

    The moral of the story?
     

    A. You are not the font of wisdom. If very lucky, you are the point of the pen. Rule carefully.

    B. Don't make standards based on what you learned in school. Base them on what you learned in real life.

    C. If an Old Fart tells you that one of your edicts is stupid, don't assume that they're resistant to change just for the sake of being crotchety. Maybe they learned something useful over all those years and all those lines of code.

  27. Re:Standards by blank89 · · Score: 2, Funny

    int beersOnTheWall = 99;
    while(beersOnTheWall>0) {
       me.chugBeer();
       beersOnTheWall--;
       System.out.println(beersOnTheWall + " bottles of beer on the wall...");
       }

  28. Re:What a question! by geekoid · · Score: 2, Insightful

    I would write people up, and see that it was reflected in there perfomance review.

    You work for me, you do it my way. If you think your way is better, present it to me and tell me why. "Cause it's the way I do it " doesn't count.
    I'll train you, I'l give you time to set up your editor so it automates whatever you need automating. I'll mentor you, have other developers mentor you. But there is a line where I expect the developer to be up to speed.

    --
    The Kruger Dunning explains most post on /. http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect
  29. Standards by umbrellasd · · Score: 3, Insightful
    Current place we have a corporate naming convention document which addresses the various environments that we work with. Formatting conventions are unspecified, so everyone in our group does what they want to do. I typically use an indenting scheme that is pretty standard for most .NET articles that I read or code that I encounter (because much of my work is .NET). For the most part, we just focus on being consistent to our own approaches and the most important thing is being accepting of different ways of doing it.

    I think the most important policy is to slap the guy that says, "I like tabs more than spaces" or "I don't like the way you indent" or "I hate the way you put spaces around ('s".

    Honestly? These people have too much free time. People use a variety of conventions and I've seen pretty much all of them. As a senior developer, I just take everyone's idiosyncracies in stride, even when they name variables retarded things like: n, vt, pkq, and rsptln.

    If I can deduce what they are doing easily, it is no problem. If I cannot, I make them explain it. If they are not around anymore, problem solved. I rewrite or have their stuff rewritten in a good way, since the stuff was 99% likely to be utter crap anyway, and move on without a moments hesitation.

    I've worked on a lot of large codebases and I've never encountered this idea of, OMG this code is so archaic that I cannot possibly decipher this person's intent--and believe me, I've worked on some crazy ancient crap. My obligatory developer arrogrance leads me to state that people that cannot figure out code because of coding conventions are weak developers. Anyone that has slogged through the convoluted "efficiency" of Knuth or the a,b,c,i,j,k madness of Wirth can figure shit out.

    So anyway, if you have the authority and your people are actually willing to go along with a standard without a huge hullabaloo, then just pick any standard (you'll get way more mileage from just sticking to a consistent convention no matter what it is). If people are going to make a big deal of it and it is difficult to enforce, just deal with it individually and tell people to write sane things. Their coworkers will provide quite good feedback if they are producing shit, and that's where you really need to step into your lead role and work out a resolution.

    One of your best tools for a standard is to create automation to enforce it. Get yourself some prettyprint scripts that you have run on all source that is checked in--in fact, get your developers the same tool so they can run it on what they check out to print it the way they like it. (Of course, you only want to check the source in with the standard pretty printing or diffs become atrocious, but that's technical stuff for a different discussion.)

    Bottom line is that whatever you can automate in the way of conventions is a win because then it's completely automatic, difficult to bicker about (two coworkers can't very well bicker at each other when it's the prettyprinter's fault, so they can only come to you and you have authority to resolve the issue right quick, whereas they could just engage each other in an endlessly unproductive slugfest if they are coding by the convention of their opinion), and if people want a change it goes through you and you have a strong argument for--"if it isn't broke, don't fix it".

    Kind of a ramble, but after many years this is my take on standards. Use a convention if it is convenient. If not, play it a bit more loose, but be firm on snuffing out those annoying neverending debate situations.

    That said, one factor that is relevant is the type of work you are doing. I'm assuming from what you said that you have some flexibility to structure as you like. If for instance you were subject to government or other agency auditing (my current company is), then the loose method is not going to fly, but on the other hand, you would probably already know what conventions you needed becaus

  30. #defun is sooo 70s... by PaulBu · · Score: 3, Informative

    enum is your friend!

    enum {LOAD_DATA, SAVE_DATA, DESTROY_DATA} ...

    Paul B.
    P.S. And of course my all-caps enum values were considered too lame by lameness filter... ;-(

    1. Re:#defun is sooo 70s... by Bill+Dog · · Score: 2, Informative

      And enum values in all ucase are sooo 80's! ;-)

      enum DataAction
      {
              eLoadData,
              eSaveData,
              eDestroyData
      };

      --
      Attention zealots and haters: 00100 00100
    2. Re:#defun is sooo 70s... by goonerw · · Score: 4, Funny

      And Hungarian notation is soo 90's ;-)

      --
      LOAD ".SIG"
      PRESS PLAY ON TAPE
    3. Re:#defun is sooo 70s... by Fembot · · Score: 2, Funny

      LOAD_DATA + SAVE_DATA == DESTROY_DATA??

      (Yes, that's compiler implementation specific, I know...)

      Alan

  31. Dilbert by RedNovember · · Score: 2, Funny

    heh

    --
    "MY APOCALYPTIC TENOR HAS NOT BEEN DISPELLED!" - T-Rex, qwantz.com
  32. Geek minds by eric.t.f.bat · · Score: 4, Insightful

    The best description I've ever come up with for the Geek mindset is this: a Geek can hold a complex structure in her head and manipulate it with ease. A History Geek can hold the structure of a historical event and see motivations and causes from every angle; a Carpentry Geek can plan an entire piece of woodwork and see every cut and join vividly; a Programming Geek can hold a program's structure and its data and event flows and manipulate it as an idea.

    Someone commented that the difference between Microsoft and Google is that Microsoft programmers are holding concepts the size of "If...Then...Else" and Google programmers are holding concepts the size of Bayesian filtering; thus, Google's Geeks are better at making big, coherent plans without getting lost in the details. It's not 100% true across the board, but it's an insight.

    As a Project Manager, then, your job is to:

    1. Allow your Geeks to transfer the concepts from the screen/page/whiteboard into their heads; and

    2. Allow your Geeks to hold those ideas easily once they've got them.

    Step 1 is a bandwidth issue: make the "inputs" more efficient by, for example, giving all of them dual-head monitors and high speed printers, so they can get lots of code into a usable format for reading (some of us prefer printouts; others just need vi/Emacs and a flicker-free monitor). Step 2 is a quality issue: Geeks who have to hide in headphones or run away to the park to read because of ringing phones and nagging managers are NOT going to be able to do their job.

    And with any data pipe, throughput is more a function of time rather than pressure. So your dream of getting your programmers up to speed in minimum time really is -- pardon the pun -- a pipe dream. They won't be any use to you if they don't have the time to learn the systems they're working on.

    --
    I have discovered a truly remarkable .sig block which this margin is too small to conta
  33. I recommend the Mercury project model by ralphbecket · · Score: 2, Insightful

    Mercury is an industrial strength, state-of-the-art
    compiler for a declarative programming language
    comprising some half a million lines of code. The
    project has been running for over ten years with
    multiple developers working at any given time, some
    of which are in different locations.

    Key aspects of the development model are:

    (1) Use a good source code control system (we use cvs,
    but are considering svn).

    (2) Add at least one test case for every piece of
    functionality you add to the system and for every bug
    that is discovered during use.

    (3) Use a robust, automated build-and-test system.

    (4) All code changes should (a) compile, (b) not break
    any test cases, and (c) -this is vital- pass peer
    review on a mailing list.

    (5) All code should be adequately documented. Every
    change should be accompanied by a log message explaining
    the rationale for the change and what the changes were
    and a unified source code diff.

    (6) Have a common coding standard for things like
    naming, layout, commenting, and preferred idioms.
    Shoot any coders that use more than 79 columns in
    their code.
    Avoid complexity and cleverness unless it is absolutely
    warranted.

    (7) Code should check all error conditions. Exceptions
    are rarely a good error reporting mechanism.

    (8) Have nightly builds and test runs.

    (9) Your watchwords should be discipline, cleanliness,
    simplicity.

    -- Ralph

  34. Never comment! by Billly+Gates · · Score: 5, Funny

    Its for wussies!

    -USe tons and tons of goto statements.

    -Make sure you use particular letters capped for variables of different types to make them more confusing for the losers who can't read the code and remember what each one was.

    - always make calls by reference using pointers as arguments. Don't use call by values.

    - Hell user other pointers that use other pointers to make things more interesting. Reassign them all over the place

    - Never use a three tier model when developing client/server apps. This only creates redundancy and gets in the way of solving the problem.

    - When linking to a database always use vendor specific extensions and avoid a database layer using something like odbc. It makes use of the advanced feature set by the particular RDBMS.

    - Be a man! Show how much you know perl. Alot of one linners can save tons of time with exotic line switches

    Oh last... make tons of money and gain job security because no one in Earth will be able to understand or work on your projects after doing all of these things. Enjoy

    1. Re:Never comment! by MagicMerlin · · Score: 2, Interesting
      - Never use a three tier model when developing client/server apps. This only creates redundancy and gets in the way of solving the problem - When linking to a database always use vendor specific extensions and avoid a database layer using something like odbc. It makes use of the advanced feature set by the particular RDBMS


      umm, it sounds to me like you are one of legions of 'application level' programmers. the separation of an application into 'tiers' (which have no real formal definition) just obscures data contraints into a maze of levels of code. Totally unnecessary...the closer your constraints are to the actual data the cleaner and more maintainalbe your application will be.

      Very few applications need to be portable across databases. If you pick a good database (PostgreSQL), there is little reason to port. Application languages (ruby, c++, COBOL, Java, etc etc etc) are a dime a dozen and will be switched and/or mixed a dozen times over the lifetime of a enterprise app.
  35. Ahahahahaaa... heh... Snrrrrrkkk. Kidding, right? by pla · · Score: 5, Informative

    without wasting a couple hours just to figure out the code.

    A couple hours???

    Look, no offense, but you either only deal in "toy" code, or you have such high expectation that you will fail, and quite spectacularly.

    A new coder, even an experienced one, takes days or even weeks after coming into an existing project before he can contribute anything but the most trivial of changes. For a truly massive project, or one that requires intimate domain-specific knowledge in a niche industry, extend that to months.

    If you can find a way to get an unfamiliar newcomer up to speed on any "real" project in a matter of hours, consider your talents wasted in your current position.

  36. Fundamental coding truths by WiMoose · · Score: 5, Insightful

    In addition to some of the suggestions made so far I would add a good automatic regression-test system which runs every night, and reports problems (build failures or result diffs). I've made mine so they "find the guilty" (whoever committed code since the last good regresstion test).

    I recently put together a list of Fundamental Coding Truths after musing about this topic and why it was so hard to plan software development:

    1. Software is not at its core a collection of a few clever algorithms.
          Rather, it is primarily (in the ways that matter) a huge collection of arbitrary
          choices and random implementation details.

          The algorithms that consititute the mathematical/logical basis of a piece of software
          are an important, but very small (eg: 1%) and relatively very simple part
          of the overall code.

    2. Code complexity is pretty much exclusively determined by the (combinatorial)
          number of interactions between pieces. Each interaction requires at least one decision
          and usually many more.

    3. Because of #1 and #2, deep, intimate familiarity with the code (this vast
          collection of implementation details) is only ever fully knowable to the original
          author(s) who made these uncountably many, mostly arbitrary decisions.
          (Familiarity by secondary authors/maintainers comes primarily from
            re-writting sections of code.)

    4. Because of #3, programmers are not interchangeable. The efficiency with
          which a person can navigate the code, implement or even imagine changes
          is almost entirely determined by how familiar they are with these many, many small
          details. The ratio of efficiencies between a primary author and another
          equally talented coder is very large (eg: 100). Because of this, the original
          authors of a section of code are usually the only ones who are ever able to efficiently
          modify or restructure it. This becomes rapidly more true as the the size and
          complexity of the code increases.

    5. Because of the complexity of code (the number of interactions and interdependencies),
          debugging and maintenance constitutes the vast majority (eg: 99.9%) of the work
          required by a piece of software over its life.

    6. Because of the complexity of code (number of interactions between components), it is
            very hard, if not impossible, to predict with any accuracy what will be involved in implementing
            a given change. Even for original authors, unintented side effects are almost inevitable, and
            the primary determinant of the length and difficulty of a task lies in finding and rectifying
            unintented consequences or unforseen interactions. Because of this, the uncertainty in the time
            it will take to execute a change is very large.
          (eg: 10x range in 95% confidence limit of time estimate, say 1 day-2weeks).

    7. Because of the complexity of code, bugs are an inevitable byproduct of writing code. It is hard
            to predict how long it will take to find and repair bugs as that depends on how many side effects are
            involved, which is not known until the repair is done and "fully tested". The only way to avoid bugs
            completely is to not write code. There are things that can minimize bugs or speed up finding/fixing
            them, but they will always exist.

  37. Re:What a question! by chromatic · · Score: 3, Funny

    Perhaps someone broke in and fixed the code.

  38. Coding Standards by NiftyNick · · Score: 2, Informative

    I know what you mean about coding standards. I have worked in so many places and have been asked "Do you have any coding standards that we can use". So instead of carrying around stacks of documents, I have placed them all on one site. Go to Delphi Coding Standards this is a Delphi coding standard I follow, but I'm sure you can apply it to all languages as required.

  39. Ideal workplace by pmv · · Score: 2, Interesting

    I'm sure many others here have already gone on and on about coding practices, so I'll go in other important directions.

    Beanbags. Very useful. Especially when you've got those incredibly stubborn bugs, and feeling careless and jumping about and falling. *grin*

    Food and drinks (coffee). Increases productivity greatly.

    I've also appreciated how the QA team is ideally located in separate offices from devel. Things get pretty messy. :)

  40. Even better: CPAMAP by gerf · · Score: 2, Funny

    (copy paste as much as possible)

  41. For .Net, here is what we use by cyberjessy · · Score: 4, Informative

    C# - The C# Coding Style Guide, Mike Krueger(SharpDevelop). This is probably the most widely used one (Novell). It largely agrees with Microsoft's internal coding standards, with a few exceptions.
        VB - .Net Coding Standards, part of the SDK. This is not comprehensive though, like the C# doc mentioned above.

    Version Control -
        Server: Subversion + Apache
        Client: Tortoise SVN (Excellent) [We also use Perforce, CVS, VSS(Commercial apps)]
    Continuous Integration - Cruise Control.Net
    Intranet, Knowledge Management - DotNetNuke (www.dotnetnuke.com)
    Project Management - dotProject (PHP) (www.dotproject.com), MS Project
    Unit Testing - NUnit (www.nunit.org)

    --
    Life is just a conviction.
  42. Coding Style by Anonymous Coward · · Score: 2, Insightful

    This is a subject near and dear to my heart. I have a history of coding in small shops, from 1 to 7 programmers. I currently work with two other programmers at a company that has had 4 programmers before us that are no longer available to us. My coding style is very different than my coworkers'. My code is very dense, with few comments, because I believe the code is the comment, and frankly, I think if a compiler can understand it I should be able to also. But that's not important here. I think it is useful that we all have different coding styles. In an environment like mine that has only a few players we learn each others style and know who did what just by the way it looks. It's also nice to see where one person has modified another person's routine.

    I love good variable names and statements of purpose and all that, but I think pure conformity is counter productive. Whatever guidelines you put in place, if you allow for some differintiation between authors it will help with the debugging later.

  43. Standards are irrelevant by dpbsmith · · Score: 2, Insightful

    It's funny. I work very closely with two other programmers, although we work on almost disjoint bodies of code. Our coding styles vary widely. One of us uses Hungarian notation, one of us does not, one sometimes does and sometimes doesn't. We use different indentation styles, different nesting styles, different personal styles for naming variables.

    And you know what? None of us have any trouble at all reading or maintaining each other's code.

    Why? Because we're good programmers; because we _care_ about what we are doing, we take a long-term approach, and management judges us by our long-term track record and doesn't look over our shoulders micromanaging how many spaces we indent.

    And we all write LOTS of comments, but we comment the things that need to be commented, not just pro-forma and CYA stuff.

  44. You want documentation, not coding standards. by oneiros27 · · Score: 2, Insightful
    Don't get me wrong, coding standards help too, but by the question:
    Right now I'm more concerned about trying to set up coding standards, so that any developer can jump into any part of a project and be able to figure out what's going on, without wasting a couple hours just to figure out the code
    I couldn't care less if people are using tabs / 2 space indents / cuddled elses / whatever formatting crap.

    Even how you name your variables vs. functions vs. methods vs. objects has very little to do with being able to jump into a project, so long as people are consistent. What's more important, is to maintain good documentation, so that someone has some clue what the relevent files are, and what the overall logic was in how the program / general modules / etc are laid out.

    No one is going to be able to jump in and start modifying code on a moment's notice. On a large project, spread across multiple developers, it might take a week or more for someone to have a grasp of what needs to be done, why it's being done the way it is, and what the implications are to change things to the way that they think is better. (I consider unit tests to be a form of documentation -- given a specific input, I expect the given result)

      And let's not forget the whole mythical man month -- tossing in another developer at the wrong time may screw up the existing developers if they get pestered by the newbie. That's why I try to keep documentation explaining what the purpose of the project is, known outstanding issues, how the program is laid out, all of those sorts of things that a new developer would need, should I get reassigned, fired, given extra help, or just give up and decide to quit.

    A ticket tracking system, and some centralized documentation repository (might be a wiki for multi-person projects) can really help you get a handle on these sorts of things.

    If you want actual programming tips ... take a look at Damian Conway's Best Practices article for perl.com (or his book) ... much of it applies to more languages than just Perl.
    --
    Build it, and they will come^Hplain.
  45. Doxygen by everphilski · · Score: 2, Informative

    In C++ we use Doxygen. Basically as you write comments inline you use a few shorthand markers (kinda like HTML tags, sorta, not really) to tell Doxygen what to pick up. Generates pretty good documentation and graphical class charts, etc. Works pretty slick, Doxygen is then pure HTML + png documentation of your code.

    -everphilski-

  46. Excellent Book by weegreenblobbie · · Score: 2, Informative

    I have recently aquired the book "C++ Coding Standards - 101 Rules, Guidelines, and Best Practices." ISBN 0321113586 or http://www.amazon.com/gp/product/0321113586/103-00 42056-9954216?v=glance&n=283155/

  47. Coding standards by El+Cabri · · Score: 2, Interesting

    Coding standards are language standard, or language specifications.
    A developer who does not understand any piece of code does not understand the language and hence is incompetent.
    Of course one can write obfuscated code, and developers should be encouraged not to. If your developers are not capable of writing meaningful code in a language, change the language, change the developers, or as a last resort change careers, your company stinks.
    Setting coding standards would be the same as restricting the English language to a subset in which, for example, George W Bush would be capable of forming a meaningful and consistent sentence.

  48. Re:Comments lie by rs79 · · Score: 2, Insightful

    " and finding out that those things no longer apply because somebody changed a 1 to a 2."

    Comments lie. Code never lies.

    --
    Need Mercedes parts ?
  49. You don't have to come up with anything... by Lairdsville · · Score: 2, Insightful
    If your company has been doing development for 35+ years in multiple projects, there is certainly a body of knowedge and culture of development that has evolved over the life of the company. I doubt that you could just 'come up' with anything better yourself, so I think your goal would be most effectively achieved by collecting and organising the information that you have all about you.

    I achieved a similar thing in my company by setting up a wiki (I started with Twiki and then we changed to Confluence) with a basic skeleton that I wanted have fleshed out. I even got our developers to define the skeleton, they all knew what we needed, code guidelines, review methods, development procedures etc. Now all I have to do is spread the word about the existence of the wiki and watch it emerge!

  50. Code Complete by pigwin32 · · Score: 3, Informative

    Steve McConnell's Code Complete is an excellent source for coding standards and a good read for any developer. I don't agree with everything in the book but it is comprehensive. Ignore that it's published by Microsoft Press, it's a good one.

  51. Don't just worry about coding pratices... by megalogeek · · Score: 2, Informative

    You should also worry about development practices. Just having good coding pratices will not gain you much in the way of robust and easily changed systems. Having good development pratices will.

    Specifically, I'm referring to having a complete system of specifying the requirements for any system. Too many coders these days start a project by hacking up the first thing they think is necessary, then the second, then the third, etc. While this ends up working out for most small projects, big projects can quickly become unweildy. Not to mention, if you bring in a new developer after years of working like this, the learning curve for that developer is very steep.

    Enter Hatley & Pirbhai's Strategies for Real-Time System Specification. In this book, the authors outline a set of strategies for developing complicated systems and making them as robust as possible. Now, you may be thingking "Who are these guys and why should I care what they have to say?" Well, they used to work at Boeing and they developed their strategies while working on designing a plane. (I think it was the 777, but I could me wrong.)

    You should definately read the book, but the strategies they present basically boil down to defining the whole system from the perspective of what, how and when--separately. Here's how it works:

    • Specify what the system does - This means starting at the top and drilling down until you get down to individual tasks that do one thing.
    • Specify how each task will be implemented - This is where you write the code, develop the hardware and such thing.
    • Specify when (and how often) each task needs to run - If you find some task can't be completed as often as you like, it's easy to go back to the implementation and find a new way to do it.

    This may seem like overkill, but it's not. I've been working like this for a few years at college now and it has huge advantages. Development tends to go faster, problems can be fixed faster and--most importantly I think--new developers can sit down with the specifications and get up to speed very quickly.

    Overall, I think using strategies like Hatley and Pirhbai have developed is far more important than all the coding practices and code commenting in the world.

    Of course, YMMV, etc.

    --James
  52. Re:Comments lie by Lehk228 · · Score: 5, Informative
    Comments lie. Code never lies.
    I beg to differ
    --
    Snowden and Manning are heroes.
  53. Re:Question about Hungarian Notation by Lehk228 · · Score: 2, Interesting

    Hungarian notation puts an unenforced comment into every variable name.

    the problem is not when you look at intPositionSensorReading but rather when it has been changed to a decimal, or when you need to change it to a decimal suddenly you are either wasting time editing every piece of code using that variable. or you cause incorrect comments to be all over the code.

    IFF VB would enforce and automate hungarian notation as an option it would be useful (i use VB as the example because it is the only place i have run into Hungarian Notaiton)

    More HERE

    --
    Snowden and Manning are heroes.
  54. Re:Magic Numbers by WushuJim · · Score: 2, Insightful

    In addition to that, don't hard code values into variable names such as making a timer variable called fifteenSecondTimer.

  55. Pragmatic by dividius · · Score: 3, Informative

    Read and apply the Pragmatic Programmer.

  56. Watch Your Cornhole by krisamico · · Score: 2, Interesting

    I see a lot of comments in this thread about coding practices and the like. That is fine, but I think you would do well to think about practices that matter more. You have indicated that your environment really doesn't offer much of an IT infrastructure, which means that you will more than likely play an appreciable role in many of the following processes: requirements management, quality, change management, project management. There may be many instances of your behavior causing projects to succeed or fail, and they will have nothing to do with whether your people are commenting their code.

    If you can, put together a process that specifies how all of you can define a product, start a project (get a suit to sign off on it too), deal with changes in requirements without tanking the project, assure quality, and ship. The code will take care of itself because it is the only thing you will have a decent amount of control over. Everything else is cross-functional, which adds a great deal of difficulty -- hence the need for policy.

    Just remember the "ship" part. Don't get stuck too long in defining a process because none exist which are universally indicated, completely effective, or free from ruinous meddling and circumvention. Worry more about what can keep you from shipping and try to set a policy that will prevent those things.

    And most of all, watch your cornhole -- technical leads are sh*t magnets.

  57. What we do by InAbsentia · · Score: 2, Insightful
    Small shop of 12 coders about 98% java code. Total source under version control 270,000 lines of code plus 130,000 lines of unit tests. We use cvs for source/version control.

    The most important thing is AUTOMATE everything that you can.
    We run a cycle where we do an automated checkout every 15 minutes. This is compiled and the checks below are done on all packages that have been updated or which raised errors the last time. Every three hours we do a zero base checkout and run tests across everything including running all unit tests. We also then do a complete construction of installers etc. for the products we ship and run tests on that (rather than in the developer environment). We also checkout across multiple platforms and run the unit tests on these (this is a bit more irregular). The results are collected on a company internal website and errors cause a real-life set of traffic lights to turn red (everyone can see them).

    The things we automate include:
    • style checking (checkstyle) and some other similar packages
    • spelling
    • javadocs on all publicly accessible methods
    • running unit tests
    • we check the unit tests by running a mutation tester which checks how well the unit tests cover the code

    There is more to testing than this but this certainly deals with the low level coding stuff well.
  58. partially agree by xswl0931 · · Score: 2, Insightful

    If code is written well, it should have few comments as the logic should be fairly obvious. In the case of if (x == 456), this should really be something like "if (STATUS_BUFFER_FULL == statusCode) ..." now it's obvious what is going on. Descriptive variable names and method names mean less comments are needed.

  59. Re:Question about Hungarian Notation by joe_bruin · · Score: 5, Insightful

    Hungarian notation has its (extremely limited) uses.  The reality is that it turns code into garbage.  Go ahead, read aloud the lines of code below.

    // the old c style
    if(cur == last) rec->tag = name;

    // camel case
    if(currentKey == lastEntry) Record->keyTag = userName;

    // hungarian
    if(iCurrentKey == iLastEntry) prRecord->m_pszKeyTag = pszUserName;

    Now imagine discussing them with your coworker.  Imagine thinking in your head "What should I do if prRecord->m_pszKeyTag is NULL?"  Humans are good at symbolic manipulation.  Giving something a name makes it easier to deal with.  Giving something a label that cannot be easily manipulated in language (spoken or in your head) severely hampers the ability to think it through.

    The argument for Hungarian is usually "but it lets you know what the variables are".  This is the maintainance programmer argument.    This argument rarely makes sense in reality, unless some very bad programming is involved.  First of all, if you do not understand the current code you are about to modify, you should *not* be modifying it.  If your maintainance programmer is just going to have a look at two lines of code, add a third in the middle, and hope for the best then you are truly fucked.  He has obviously not understood the code enough to know what the consequences of the modification will be.  The reality is, if your current logic unit is such a monstrosity that looking up the types of your variables is a burden, and your variable names are so poor that it is insufficient to infer at least a basic understanding of what is going on without having to resort to prepending types, you should probably step away from the keyboard, turn off your computer, and tell your boss that you had an epiphany and will be pursuing a career in French fry development.

  60. Some of my rules by gregm · · Score: 2, Insightful

    I'm not really one for coding standards, just make each person maintain a certain level of consistantcy and make damn sure they make good comments. You might want to institute some common variable naming scheme. Here are a few rules I've come up with over the years.

    1) Thou shalt NOT make the user re-enter data
    2) Waste not clicks for they are precious
    3) Thou shall not design a screen that hath no purpose
    4) Move not your bits about the screen like a drunken stripper
    5) Gulp not your data but merely sip... as it makes reguritation less lumpy
    6) That which the user doeth the most, shall not be obscurred by that which he doeth least
    7) Dress not your screens with vain and lustful colors that are without purpose
    8) The user is the one true god and thou shall hold no gods before the user
    9) The user is a friggin idiot
    10) An image that measures 16 pixels across and 16 pixels along it's length is rarely worth one word

    G

  61. I keep my own log book for programming by Cappadonna · · Score: 2, Insightful
    I'm a freelance developer for a day trading firm and a PACS/RIS** administrator for municipal hospital, so most of my projects involve really massive planning for large amounts of data. Whenever I start a new project, I right every little component in a big lab notebook. I even right out major snippets of code, line by line. This helps me in several ways.

    One, when I start plunking away at the keyboard, most of my ideas have been muddled through and I'm not wasting time fumbling through books and websites to find answers. I can also note what ideas did and did not work. Also, since I am typically juggling mutliple projects, it helps me keep track of what I've done and what I have to do.

    Second, I've learned to keep it for review. Basically, I learned at my last job that documentation can save your butt, especially when working with nurse manager who still can't find her archives folder in Outlook or trying to explain how archaic software works to management when nobody has even looked at the source code in 7 years. Its a picture into my brain and its a log of where things have progressed for a give project.

    Third, my notebook has served me are my only way to figure out what the heck I'm working on. Essentially, I've always been given a massive system to rework/hack/redesign that nobody else bothered to figure out. My notebook is my only guide to solving problems, since its my only reliable reference.

    Fourth, a journal can double as a weekly to do list. Alot of times, I have so much crap going on running my system that I forget what the hell I was working on. So, I often write down 10 projects or assignments I need to do within two weeks and cross them off as I go along.

    And finally, it keeps me from having to write the same things twice. Often, I can use code snippets, data structures and old work flow schemas in other projects. that's really helpful when you're up until 12-1 in the morning hammer away at some God awful perl script and you need to get everything finished by the weekend.

    ** PACS and RIS stand for Picture ArChiving System and Radiological Information System, respectively. They are two ancillary systems that hospitals now use to save X-ray, CT, MRI and other images of the body.
  62. Meaningless Standards by BigTimOBrien · · Score: 2, Informative

    Most standards are relatively meaningless. Indentation, Spaces not Tabs, "All class names must be descriptive", "Comments are required" - really this is all hand waving. Let individual groups figure out what's best for them. And stop thinking like a boss, or you'll find yourself with no one to manage pretty quick.

    --
    ------ Tim O'Brien
  63. Good way to get rid of your best staff... by RKBA · · Score: 2, Interesting

    I wouldn't work for any company that tried to tell me what "coding style" to use. I'm a retired programmer with 35+ years of experience BTW.

  64. Domain Driven Design by Symbiot · · Score: 3, Informative

    If you want code that can be readily understood you need something other than coding conventions. Coding conventions only make the code all look the same. You can get almost all of the benefit (without most of the arguments) by saying only that each file must be written with the same coding convention throughout. The code will get prettier and prettier with tighter conventions and developers will waste less time reformatting each others code. But it won't do a thing to make your project more understandable.

    For that you need an understandable design and the best advice I've ever seen for that is in Eric Evens' "Domain Driven Design" http://domaindrivendesign.org/. The advice there will work for both Agile and non-Agile projects and its core themes are pretty much unavoidable truths about how to write code for a project that is also written about the project: use language that comes from the projects domain, insulate code from each domain or sub-domain from the rest of the world, keep each method at the same level of abstraction (that's big) and make implicit concepts explicit, to name a few. The key is for your developers to consider themselves to be authors and to strive to keep each little piece of code they write on-topic. Not only will it be easier for new developers to come up to speed but the code will work a heck of a lot better too.

  65. Re:Comments lie by mabinogi · · Score: 2, Insightful

    That depends on what you expect it to tell you.

    Comments can lie, and code never lies about what it does, but code doesn't tell you anything at all about what the author intended it to do. The comments are more likely to give you a hint, and at the very least if the comments and the code agree, you can probably be sure it's right. When the comments and the code disagree then you know that at least one of them is wrong.

    --
    Advanced users are users too!
  66. Our process by I+Like+Pudding · · Score: 2, Funny

    If it compiles, ship it. If it doesn't compile, ship it. If the users complain, ignore them (they are always complaining). If the users complain moreso than normal, work all day and night and fight with QA and the admins and the VPs to get a patch in.

    Repeat until app becomes unmaintainable. Repeat furthur. Repeat.

    I will be giving seminars on how to implement Sisyphusian Unified Process throughout the year down at the bar. If I happen to be unconcious, please leave me be - that's my "comp time".

  67. Use automatic code formatters by mophab · · Score: 2, Insightful

    Use indent for C and C++
    And Jalopy for Java.
    Formatters are available for most languages.
    Decide on what all of the options are for each formatter and make
    a script available that runs the formatter with the appropriate options.

    Require that automated formatters be run before code is checked in.

    It is easier to read consistant formatting than your favorite formatting.

  68. Coding standards by Todd+Knarr · · Score: 4, Funny

    As someone with 20+ years of professional programming under my belt, a lot of it doing maintenance and enhancement of existing code, I'll say this: most of what's considered "coding standards" doesn't much matter. Indentation, brace positioning, type prefixes on variables, underlines vs. StudlyCaps, capitalization in general, most competent programmers can pick up on any variation quickly. The few things that count are more general:

    1. Comment logic and motivation, not the code itself. I can figure out what the code's doing. What I need coming into it's what it's supposed to be doing, why the code does things the way it does, what the data structures are supposed to represent and how they're supposed to be used. On routines, tell me what the routine's supposed to accomplish, what arguments it takes in and what results it spits out (including error conditions).
    2. Make variable names descriptive. Abbreviate where it makes sense, but make the name give me an idea of what it's for. It's less important that I know it's a string than that I know it's the last name of the customer whose order you're processing. And if all it's for is the index in a loop and it's got no meaning outside of the loop, then yes i and j are perfectly legitimate names that any programmer will (or should, at least) recognize.
    3. Programmers should try to use consistent indentation, brace alignment and other formatting things when writing new code, and should try to match the existing formatting when modifying code. Emacs and other modern editors can do automatic indentation and pretty-printing for you, make use of those features and make it easy for programmers to set their editors up to match commonly-used styles. And make them clean up garbage, things like trailing whitespace and irregular alignment are disproportionate pains. I don't care much what the tab interval is, but I hate it when the interval changes every few lines.
    4. Use whitespace for readability. Code like if(strlen(obj.getname())" is legal, but it's a lot harder to read than "if ( strlen( obj.getname() ) ". It also makes it easier to distinguish functions ("f(x)") from control structures ("if ( x )"). Similarly, putting the opening brace of a loop or conditional on the end of the line may be compact, but it makes it hard to distinguish the start of a multi-line body from a single-line body followed by some lines with the wrong indentation.
    5. A few small formatting things are overall useful. Symbolic constants should be immediately recognizable as such and all-caps is a commonly-recognized way of doing that, for example. And the indentation level of the code should match the logical level, that is the "then" and "else" bodies of an if statement should be indented further than the "if" and "else" keywords (which should both be indented at the same level).
  69. As much a social/managerial issue as a tech one by crucini · · Score: 2, Insightful
    First of all, how many developers do you have? Few enough to fit in a conference room? How many languages? Do all the developers know all the languages, or are they fragmented into language communities?

    The first step is to assess the current situation - what coding practices are currently in use? What do the developers want? Can you roughly group the existing codebase into various standards, plus a pile of incoherent crap? Is it worth while rewriting the crap portion to the new standards?

    Second, decide what level of standardization you want to achieve. The more detailed your standards, the more difficult and risky. You will probably make some wrong decisions, and they will irritate developers now or in the future. However, if all your developers code in the same language, and several of you are experts, you may be able to write detailed standards and get it right.

    Third, identify relevant references. If you're working with Perl, Damian Conway's Perl Best Practices is a good choice. In C++, Meyers' Effective C++ series is good.

    In general, micro-standards will not be successful. Instead of trying to make everyone use the same indentation or something, you'll get the most bang for the buck by focusing on high level issues. For example:
    1. Require at least one Wiki page for each piece of software; in addition to any docs on how to use the software, this is a page on how the software works internally.
    2. Keep code units to a reasonable size, with a clear interface. Reduces chaos, and lets you rewrite one unit from scratch if it's written horribly.
    3. Require a peer code review of each code unit. Persuade the reviewers to read the code before the meeting so you get more than off-the-cuff comments. Experienced programmers may disagree about indentation, but they generally agree about things that really shouldn't be in your code. Comments from these reviews may crystallize into a de facto standard.

    Good luck.
  70. C++ coding style by HighPerformanceCoder · · Score: 2, Interesting

    Mostly these threads focus on comments and naming conventions. One of the most important coding styles I've adhered to for the last decade is to always encapsulate new and delete within a class. This ensures every new has a corresponding delete called when the class's destructor is called. Use C++ automatic variable declarations to control object lifetimes.
    The only time I've had a memory leak in the last 10 years was when I had to break this coding standard (eg for library compatibility).

    The second most important coding style is to use pointers only when necessary - some graph algorithms need them, and so do some "legacy" C libraries. Otherwise, use references - there in the language for that purpose.

    The 3rd most important coding style is use standard library container syntax whereever it makes sense. Even if you write your own container libraries - follow standard library conventions. Makes it much easier for other coders to follow.

    After this follow a bunch of useful stuff - eg ensure that meaningful default, copy constructors and assignments are available for your class, use the const keyword wherever it makes sense

    On the subject of naming conventions - naming conventions can lie! Tools like doxygen will quickly tell you what a particular indentifier refers to in a particular context. If not, then grep is pretty handy at working it out. However, often one wants to use the same name for type names and instance names - a convention like first letter upper case for typenames, or appended _t can help the addled brain.

    Throw open a question now - any good tips for organising namespace names, and macro names to avoid the inevitable clashes?

  71. Code cleanly and remove comment by oo_waratah · · Score: 4, Insightful

    replace a stupid name with a sensible name:

          messages_processed++;

    This actually makes sense without the comment.

    1. Re:Code cleanly and remove comment by rkww · · Score: 3, Insightful
      replace a stupid name with a sensible name:
      messages_processed++;
      That's still got potential for confusion - it could be a 'we've finished processing the messages' flag, which obviously should be a boolean, but somebody else wrote the code, so we can't be sure.

      totalMessages++;
      would be better, but it's still not perfect. Sometimes the hardest part of programming is creating meaningful variable names.
    2. Re:Code cleanly and remove comment by Anonymous Coward · · Score: 3, Funny

      Or you could turn it into a Web Service.

  72. Be picky about what you cover by try_anything · · Score: 2, Interesting

    There are three categories of standards:

    1) First, there are arbitrary choices where uniformity across the company is more important than having a perfect fit for each project.

    A perfect example is the choice of information management tools and formats. Unlike an indentation style, a source control or bug database learning curve can be a significant barrier to a developer helping out another team for a few days. It's also important to ease access for non-development personnel. Pick some tools and make everyone use them.

    "Every project shall use Subversion as its source control system, BugZilla as its bug tracking system, and DocBook for user documentation."

    Depending on the size of your company, the choice of a unit test framework or a build tool might be standardized. Keep in mind the benefit of diversity in these matters, though.

    2) Second, there are matters of practice that can be fairly unambiguously stated and checked.

    A few examples:

    "Every project shall version its acceptance tests."
    "Every project shall archive acceptance tests and test results for every software release."
    "Every project shall publish a current schedule, updated daily, and a summary of outstanding defects, updated at least weekly, to the IT intranet."
    "Every project shall maintain a system of peer review, so that all code must pass by a second pair of eyes within a week of being committed."
    "Every project shall automatically generate API documentation."

    3) Third, there are matters that may be important but shouldn't be included in your standards.

    There are two good reasons for being so picky. First, you want your standards to be as short as possible so people actually read them. Second, you don't want to publish standards that you can't or shouldn't enforce.

    An example of a good coding rule that doesn't fall into the first two categories is "Document intent, not mechanics." Everyone should do it, but checking and enforcement should be done among project teammates, not by a higher level of management.

    Another example is "Test everything that can break." The extent of test coverage can only be determined by people actually working on the project, so you can't enforce this rule. It's a great rule, but it doesn't belong in your standards.

    Since so much attention has been paid in other posts to matters of code formatting, I might as well add my two cents. For languages where there is One True Way, such as Java and Python, there's no good reason to deviate from the One True Way. Is it really your job to point out and enforce the obvious? I don't think so. Let the project managers handle it.

    For other languages, such as C++, there are a variety of accepted styles. Uniformity is good, and every project should certainly pick a style and use it consistently. Whether to pick a uniform style for the company is a judgment call. Professional C++ programmers are used to dealing with variety and shouldn't have problems switching when they jump from project to project. For your company the right rule for dealing with C++ projects may be this:

    "Every project that uses C++ shall adopt and publish a uniform brace and indentation style."

    Or it may be this:

    "All C++ code shall be formatted as in The C++ Programming Language, Special Edition."

    A final note: Be firm about setting standards, but talk to people first and don't issue any orders that you don't have the muscle to enforce. Find out what people's prejudices are and eagerly defer to them when it doesn't make much difference. Migrating CVS users to Subversion should be no big deal, but if a bunch of stubborn CVS users refuse to migrate, and you fail to make them, all the rest of your standards will go out the window as well. If your authority is shaky, the best way to shore it up is to avoid controversy and issue a bunch of commands that nobody minds obeying ;-)

  73. Re:Comments lie by bullgod · · Score: 3, Insightful
    But code can only tell you the how it can never tell you the why. That's usually more important
    I once came across a ~1400 line function of complex maths transformations with one comment

    i++ /* increment i */

    What's i? and more importantly why increment it?

  74. The beauty of slashdot :) by KZigurs · · Score: 2, Insightful

    Aaah, what a beauty. The real questions that should concern this are more in lines of the following:
    - What is a development envorement?
    - What is QA?
    - How can I test code before putting it on production?
    - How can I plan for and track team progress in development?
    - What kind of documentation will I need?
    - What is a process?
    - How do you declare/manage process?
    - Who is responsible for builds, who writes specs?
    - Do we have separate QA team?
    - Is there any testcases?
    (silly, I know, but shows the scope of his position a bit)

    YET we have 300 comments + discussion of using or not using hungarian notation in naming variables.

    Perrfect! :)

  75. Coding standards by Handyman · · Score: 2, Informative

    Here's what I like:

    1. As for code comments, rely on "Use The Source, Luke" as much as possible. Force people to write readable code, so that this actually works. Logical variable names, no unnamed magic numbers, no cryptic constructs. No loop bodies consisting of only a semicolon, e.g. "for(...;...;...);". Comment only on the things that aren't obvious. Any extraneous comments are bound to be outdated by the code, and will confuse more than help.

    2. Write down the design in comments in the source files, as a readable piece of prose containing all of the design considerations and decisions. Design of an algorithm goes in the function body, design of a class goes above the class definition. Programmers are aware that designs are often outdated, so when they read them this is not a problem. Having the design in the code has the advantage that you can actually *find* the design for the code you're looking at. There have been too many times where I've been looking for a design document that was "somewhere on the network". Or that I've been looking at a design document on the network that had been superseded three years ago. Having your design under source control fixes that.

    3. Build at least every day, or even better: continuously.

    4. Automated testing. Run automated tests on every build, if possible.

    5. Code reviews. Sit together once a week with one other team member who then reviews all your code for the last week (all of it, based on reports from source control). That shouldn't cost more than an hour or something, it's a good way of keeping the knowledge going around, it works as a very good "desensitization therapy" for those programmers who can't handle criticism, it increases communication within the team because people get to understand each other's work better. The only downside is that there is usually a lot of opposition against this -- I know a *lot* of programmers who don't like to have their code criticized. And there's a very clear risk that people will get into endless discussions about very small details of style ("should there be a space between the if and the parenthesis?") or other inconsequential things. To prevent these issues hogging the review, there should be a formal "escalation procedure", where the issue is passed on to an arbiter (team lead) with arguments from both parties. If a disucssion on an issue seems to go in this direction, either party *or* somebody else in the room whom the discussion irritates the hell out of should be able to cut off the discussion and "escalate" it. :) The team lead can then decide on a policy, e.g. "there will be no discussion on this point, everybody can do it how he/she pleases", "everybody will do it *this* way", something like that.

    Note that I'm currently working in an environment where we have (1) to (4) implemented. I'd like to have (5), because there is too many crap code being committed, and there's no check on that. It's been all too often that we've had to replace the *entire* work of a team member after he/she left, because the team member had been able to commit crap code without check during all the time (s)he was on the team.

  76. The Practice of Programming by orbitor · · Score: 2, Informative

    I make sure that every new technical hire to our company reads this book by Kerninghan and Pike. Then, I give them a copy of our coding standards which really just outline the syntatic sugar. If the person was bright enough to get hired, they are more than capable of understanding and applying the concepts presented to them through these two sources.

  77. !(How to write unmaintainable code) by fbonnet · · Score: 2, Informative

    Read this thoroughly, and try to do the opposite.

  78. Re:Comments lie by Lehk228 · · Score: 2, Funny

    disassembly can lie if the operating environment or hardware is bugged (either error or with malicious code)

    the only truely trustworthy code is code hand compiled to run on a tube CPU which you have personally blown the glass and formed every tube.

    --
    Snowden and Manning are heroes.
  79. Do you think coding standards will help? by SLOGEN · · Score: 2, Interesting

    Most people who advance coding standards talk about how braces should be put and whether there should be used braces in one-line if's, maybe they even mention the horrible and feared Hungarian Notation. I have yet to find out how any of this *actually* helps understanding code.

    Readable code is a prerequisite for understandable code, education is a prerequisite for understanding.

    Coding-standards is trying to apply a method of syntax to an education-problem, it's not gonna work. Don't think that coding-standards will give you readability, much less understanding.

    My advice is to get a few people with experience, solid, broad knowledge of the language and a pragmatic attitude to sit down and pair-program with the people who write hard-to-understand code and those who have a hard time understanding code that should have been easy to understand.

    Let people present idioms, discuss patterns and create a place where "readability" is a code-quality and a goal. (BTW: Don't fall into the "everthing is a pattern"-trap) This is not a coding standard, it's an education of "this-way-works-well-for-this-and-that".

    Promote knowledge of the language standard-library, instead of duplicating it yourself. Learn to shun "wrappers". Use the language-features for what they were meant to do, not for insert-really-cunning-hack-here. Model things as they are, instead of cutting coreners or adding complexity.

    Check out c2.com http://c2.com/cgi/wiki?WelcomeVisitors it's really a place worth knowing. Read the dialogs, they may not all be truly insightfull but they provide you with excellent examples of what people think about in development and why it's not that easy to do-the-right-thing.

    One specific thing i've found is that most people write code by copying (atleast a skeleton) from somewhere else. Accept this, and to give them something *proper* to copy from, short, complete programs -- taken from real situations, Not crappy code-project articles where people try to show off how complicated a technique they can master.

    --
    SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
  80. Re:Comments lie by kibbylow · · Score: 2, Insightful

    Comments often get in the way of code readability. I often get annoyed looking at comments like these:

    // initialize index to zero
    index = 0;

    // if string is null return an error
    if (string == null)
        return error;

    // get the next index
    index = getNextIndex();

    Comments should be reserved for describing functions and non-intuitive variables or code blocks.

    I find that having naming conventions for variables, classes and functions is very important. Using proper names makes reading the code so much easier and eliminates the need for useless comments like the ones above.

    I remember back in my first or second programming course they said, "you should be able to remove the code, read the comments and fully understand what the code is doing". I never agreed with this statement.

  81. In addition... by SeanDuggan · · Score: 4, Insightful
    The general theory of coding practices: Don't be a moron.
    More importantly: Don't be too clever.

    It's when people try to get clever in their coding that it gets hard to read. And, quite frankly, that's the code that generally breaks most easily.

    --
    This sig has absolutely no significance and serves only to take up screen space and waste the time of the reader.
  82. Re:Comments lie by xaque · · Score: 2, Insightful

    but what if aliens replaced your glass tubes with dynamite when you weren't looking?? it's better to just not code at all, and spend your life hiding in a cave armed with a pointy stick.

  83. You should still know by bluGill · · Score: 2, Insightful

    I hate Hungarian because you know the type from the context anyway. You don't do addition on a list. You don't do foo[bar] on a real.

    A variable should encode everything you need. A variable strSql isn't as useful as selectFoo which tells you what you are doing with the variable. The the variable contains sql is obvious from the context where you care about the contents, and you tells you what it is for where you don't care about the exact contents.

    1. Re:You should still know by bluGill · · Score: 2, Insightful

      Sadly strSql isn't a made up example - I was looking at code that used it while I wrote that reply.

      qryLogin, is useful because it tells me what is going on (even more than the replacements I came up with). If the prefixes have meaning I do not objects. The datatype however is rarely meaningful.

      Where you use data type prefixes is with a variable like userID. Is it an int or a string?

      You do not care what type userID is! Does it make sense to do userID + 1? No, so even if it is an int you don't treat it like an int - it is a userID. If userID was a string, likewise you do not do string manipulation on it, so it doesn't matter that from context you are unsure what it is (though I would object that it should be userName).

  84. looong functions by namekuseijin · · Score: 4, Informative

    "I once came across a ~1400 line function"

    This is so fucking wrong and wicked the programmer who did it should go straight to hell. I'm sure there's no functional coesion in there: most likely there are many disparate tasks that should be each in its own function and called from there. I'm sure there is a lot of cut-n-paste in there that should be each in its own function and called from there.

    I'm sure you can guess where i'm willing to get to... more important than hungarian notation, comments or documentation in PDF format is abiding for these 2 simple rules: KISS -- keep it simple, stupid -- and DRY -- don't repeat yourself. Once you do it, coding and reading code is a lot easier.

    So, my advice:
    * Give meaningful names to important, global, business rules variables ( local variables like i or c are ok, since they are mostly irrelevant ) or functions/methods/procedures/subroutines
    * Write short, highly coesive functions/methods/procedures/subroutines
    * Stop the cut-n-paste madness! If you do it a lot, it's obvious the copied code if begging to be parametrized and be given a name. Programmers altering your original code will be thankful
    * Write modular code, not a plain, huge, stupid monolithic wall of letters. Even in languages with no namespace support ( C/PHP etc ) a good naming convention for functions of a certain module/header can do wonders...

    * and please: meaningful names don't mean phrase-like names like thisLocalVariableIsCool. Conciseness go a long way towards good readability...

    --
    I don't feel like it...
  85. Code Review is Good by oldCoder · · Score: 2, Insightful
    Publishing coding standards about comments, variable names, subscripts vs pointers and indentation tends to generate a document that dies after 3 months. A waste.

    Have an opinion on all the above but some of your best coders might disagree. And might not agree with each other.

    Code reviews for bugs, design, format, readability et cetera are a good way to improve code quality and application quality. Code reviews are very difficult to perform and very difficult to manage.

    The idea of code reviews is so old that the older recommendations say you should review before your first compile! Find a newer guideline. The most important guidelines are about the emotions involved in code review. People can get very accusatory and very defensive.

    One way of doing reviews is pair programming.

    You will find as you go along that many managers and customers simply do not want higher quality if it delays first release. Chew on that.

    Think in advance what you will do if you find you have a good coder that nevertheless produces code that is too hard for others to understand. Rather than canning somebody, perhaps you can help the coder to express him or herself more clearly, and help teach the other one to read code more effectively.

    Code reading is a specific skill and may be a specific natural talent. That is, different from the skill and the natural talent of code writing.

    Code reviewers, testers, managers, and others often have a legitimate need to add comments and/or links to production code ("bug #1234 crashed here", and "I don't understand this", and "90% of the cpu is used here"). It would be good if there were a version-control and text-editing system that allowed non-coders to add "yellow sticky notes" to code -- without breaking the build!

    --

    I18N == Intergalacticization
  86. Re:Question about Hungarian Notation by ColdSam · · Score: 2, Insightful
    I rarely use Hungarian, but your reason for not using it is awfully contrived. In your example how would you ask the question using your own naming convention?

    "What should I do if open paren capital R ecord dash greater than capital K ey capital T ag equals equals null close paren?"

    If we used Hungarian and I were to ask the question of a coworker, I would of course leave off all the crap (unless it were relevant). Humans are good at that and Hungarian notation makes it pretty easy to spot the "real" name (just skip everything until you get to the first capitalized letter).

    You may have a point if you are instructing a coworker in what to type into his editor, but if that's the case you probably have bigger problems with your development team.

  87. Re:Comments lie by 2short · · Score: 2, Funny

    My favorite was the entire huge module with only one comment: /* Make sure j != 2 !!!*/

    No sign of a variable named j anywhere...