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

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

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

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

    7. 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.
    8. 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
    9. 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?

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

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

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

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

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

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

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

  10. Re:Comments lie by Lehk228 · · Score: 5, Informative
    Comments lie. Code never lies.
    I beg to differ
    --
    Snowden and Manning are heroes.
  11. 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.