Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Recommended C++ and Java Coding Standards? 40

Gerard J. Pinzone queries: "My company is looking to implement C/C++ and Java coding standards. However, I can't seem to find a definitive list. I'm more familiar with Java and have suggested that we use 'Elements of Java Style' and Sun's documentation. BTW, beware of 'Netscape's Software Coding Standards Guide for Java.' It's woefully out-of-date! Any suggestions?"
This discussion has been archived. No new comments can be posted.

Recommended C++ and Java Coding Standards?

Comments Filter:
  • Try this (Score:3, Informative)

    by pong ( 18266 ) on Sunday December 23, 2001 @07:06AM (#2743912) Homepage
    Coding Conventions [macadamian.com]
  • C++ standards (Score:2, Insightful)

    by Kirruth ( 544020 )
    For C++, Stroustroup's home page offers a solid set of advice and links:

    http://www.research.att.com/~bs/C++.html

    Since he designed the language, I guess he is authoritative.

    If portability is important or if you are likely to Open Source some of your code, Mozilla offers a great style guide for this:

    http://www.mozilla.org/hacking/portable-cpp.html

    C++ compilers are still contrary beasts, and it is worth being aware of the pitfalls.

    A number of the tips, especially the "do's" come from Scott Meyers "Effective C++" series, which has to be recommended for anyone looking to define a common company approach to C++ programming.

    • Mozilla's standards are great, if you want to use what little bit of C++ will work on every compiler on the planet.

      This depends of course on the nature of your project, but I think it's fair to assume a non-decrepit compiler. If Visual C++ 1.5 breaks a certain feature, well, Visual C++ 6.0 has been out for over 2 years now.

      There are a lot of really useful parts of C++ that are actually fairly well worked out on most modern compilers. For instance, templates are damn handy. There may be some differences between the level of support, but there is generally a very large subset of C++ templates that works on most modern compilers. And they let you do things that make all the rest of the programming safer and easier, like generic containers, like smart pointers.

    • The Mozilla coding standards are most helpful, but are a tad out of date. For instance, wherever they say "few compilers", the more accurate term "all currently maintained compilers" can be inserted.

      This is especially true wrt templates, exceptions (some quirks on this one; I still avoid them) and C++-style comments.

      Heck, I use C++-style comments with our HP-UX 9 C compiler (some senior engineer always goes in behind me and converts them anyhow).

      Anyhow, I say (please flame me if I need it, I crave correction) that people with ISO non-standard C/C++ compilers need to ditch the commercial stuff and go with GCC (Q: How compliant is LCC on the Windows side?). That's just from a GNUphile. I certainly do not miss the bad old days of VC++, VisualAge, and Borland (don't miss ya, but I luv ya) Turbo C/C++.

      My .02
      • The comments in the Mozilla document on templates probably do need updating, perhaps along the lines of limiting oneself to the STL. Assuming people have an ISO-compliant compiler probably isn't a bridge too far these days.

        Still, it's a document I often look at - it's a good thing to know its "rules", before then proceeding to deliberately break them.

  • by zonk the purposeful ( 444367 ) on Sunday December 23, 2001 @08:57AM (#2744005) Homepage
    Use the pretty printer [sourceforge.net]

    It reformats your code (i use it via ANT)

    Just play with the settings and see what you like, it'll reformat the code to what you want.

    I just set it up here, and it works a treat.
    Saves all those source code arguments about where the squigaly brackets go.
    • One of the wisest programmers I know said:

      "Programming standards are a complete waste of time. A bunch of guys sit in a room arguing for days about placement of opening and closing brackets and then no one follows the standard anyhow. Just get a decent pretty print program and format the source the way you like it when you work on it and expect everyone else to do the same and don't waste time on coding standards."
    • This falls apart if you use version control, doesn't it? When you try to see what changed in a particular version, you get a ton of irrelevent format differences. And it can sometimes cause huge problems when you try to merge.
      • That was an issue as I understand it, but not if you integrate 'pretty' into your cvs.. i.e. after you submit changes it runs.

        Infact the pretty print has a built in option to support just that so that it only runs on stuff that's been submitted when run within the cvs environlment.

        Your point is good though, but I think it could be contained.
  • Heh (Score:2, Funny)

    by kitts ( 545683 )
    This is a definite must read [mindprod.com].
  • by cjhuitt ( 466651 )
    I helped develop our coding standard at work, although it is still somewhat a work in progress. Bear in mind that this is all for C/C++, but a lot of it may carry over into Java.

    I don't think you need to be reminded of the reasons for having a coding style standard, but in case anyone questions it, it undoubtly increases readability of people's code, and reduces the time needed to understand other people's code. We have also found that we are slightly better organized in how we produce code when we follow these guidelines.

    Some suggested things to think about:
    • Naming Conventions? Be sure to have all functions named the same way, regarding capitals, underscores, and that sort of thing. The same with variables, macros, and whatever else you can think of.

      For example, you might say all begining capitals for functions, such as "void OnOKButtonClicked()", first lower case then all starting caps for variables, such as "fltNewGradePercentage", and all caps for macros, such as "STANDARDSIZE".
    • Where do braces go? Some people prefer ending the line with an open brace, then indenting the next line. Others like having the open/close braces on lines by themselves, indented with the rest. Still others like the latter, but without indenting them. Find one that everyone currently there can agree on, and enforce it, so that everyone can get used to seeing the braces one way, which improves debugging and code reviews, among other things, when you don't have to be getting used to ignoring a different brace style than what you are used to.
    • How are variable names constructed? Some people have different prefixes/suffixes to signify things about the variables, such as the fact that they are global, or class members, and also what type of variable they are - ints, chars, pointers, etc.

      For example, at work, we use three-to-six letter prefixes to designate the type of the variable - intFiles is an int, chrpCurrent is a character pointer, etc.
    • Indentation Standards? Some people don't believe this should be important, but it depends on how similar your development environments are. If you all use the same IDE, then this is unimportant. If, however, you develop on Unix/Linux with a wide range of editors (vim, emacs, kwrite, etc), then indentation needs to be standardized to have the display readable on each of these. Also, do you allow tabs or not?
    • Comments? Yes, do use them. But, where are they required? The easiest place to require them is in the header for classes, for the public member functions. They should at least explain what the function does, what the arguments are that it takes, and what it returns. (I personally think that all functions, not just the public ones, need these. But perhaps that's just due to the fact that I can't interpret "int GetPtHitOn3dMseClk(int x, int y, int z)" very easily.)
    • Spaces? Spaces need to be determined - as in, where are they absolutely required. At work, we use spaces, at a minimum, between math operators and after commas in a parameter list. Other places may also be useful.

    I'm sure that there are other things to think about, which will be suggested, but these are places to start when considering a standard.
  • Face it, its one of the most used compilers in the world (if not THE most used compiler in the world). VC++ that is, and MS has their own style of notation, you've probably heard of it, called Hungarian notation.

    Very popular, a little hard to use, but will save you a ton of time.

    Did a quick search [google.com] on Google and got some really good results on how to use Hungarian notation:

    http://www.umr.edu/~cpp/common/hungarian.html [umr.edu]
    http://csciwww.etsu.edu/bailes/1250/HungarianNotat ion.htm [etsu.edu]

    Just to name a few. I use it in all of my major projects (see sig for shameless plug) and I hope that many other people will adopt it into their coding styles.

    -Vic
    • No, please don't use Hungarian notation. In particular, please don't use Microsoft's bastardized version of Hungarian. Hungarian was invented for use with untyped and weakly typed languages (think assembler). See The Great Hungarian Prefix Swindle [keysound.com] [www.keysound.org] for a well-though-out essay on the topic.

      • I use hungarian exclusively and I find that it helps tremendously for both writing code and debugging. I learnt it on the job and while it was a little confusing at first it's pretty easy to get used to if you use it continuously. The main advantage, of course is that you instantly know the type of a variable without having to look for the definition. This is invaluable for pointer arithmetic and saves a great deal of time going through compiler warnings.

        For example, the variable 'ppch' is a pointer to a pointer to a char (char **). 'p's and '*'s cancel each other so you know that the expression '(*ppch)' is a pointer to a char (char *) and '(**ppch)' is a char.

        I also prefix member variables with 'm_' so there's never ambiguity between locals and members in member functions.

        Usually the first thing I type is 'int main (int cArgs, char *rgszArgs [])'

        Of course, it's not needed for strongly typed languages like C++/Java, but I still use it because it saves me time. I've heard some people complain that it adds too much time in typing - learn to type faster...

        • For your examples, it may be good, but sometimes it's hard to come up with good ones that are readable. (Think pointer to a QCanvasPixmapArray). Sure, you could use one, but it would be tedious to type, and could get confusing. What I would do instead is make functions that do not take up many screenfulls and then you could use short names without sacrificing understandability.
          • Please excuse my ignorange, but I'm not sure what a QCanvasPixmapArray is. If it's an abstract datatype then I'd brobably use 'pqcpaExample, or if it's a (QCanvasPixmap *), then: 'rgqcpExample'. Generally such tricks don't cause any ambiguity especially given the context of the function or class that contains the code. I find that once you introduce such a mnemonic it's easy to spot its use in related code.

            Sometimes if an OS header defines a struct 'SOME_OS_DATA_STRUCT', then I'll write code like:

            SOME_OS_DATA_STRUCT sods;
            sods.foo = 3;
            ::UseSODS (&sods);
            I know it's lazy, and if I need more than one sods then I'll give them meaningful names like 'sodsThis' and 'sodsThat', but for a one-off it's not really necessary.

            Mostly I do stuff like:

            int cThings = CountThings ();
            for (int iThing = 0; iThing < cThings; ++iThing)
            {
            CThing *pThing = rgThings [iThing];
            I use STL alot too so I use alot of 'mapThings' and 'iterThing' and with ATL's CComPtr I use 'spThing' for smart-pointer. I don't adhere to the strict Simonyi notation - just enough to get by.

            It helps me a great deal. Some people turn their noses up at it - I did too at first - but I recon it's worth a try.

  • Linux (Score:5, Informative)

    by sohp ( 22984 ) <snewton.io@com> on Sunday December 23, 2001 @01:31PM (#2744621) Homepage
    For the love of Dijkstra please don't use Hungarian style. There's a lovely common style in linux/Documentation/CodingStyle [linuxhq.com] Which references (and bashes) the GNU Coding Standards [gnu.org]. Either one of those could be a good starting point, once you resolve the fights you'll get into over style.
    • what is wrong with hungarian notation?
      • I'm pleased you asked.
        • The naming hides the purpose of the variable under all the "warts".
        • If a type changes, you're forced to rename your variables to reflect the new type.
        • How do you pronounce it?
        • Encourages sloppiness in variable naming: why spend time trying to find a meaningful name after you've written the type coding warts?
        • If you don't know what your variable is for, knowing its type won't help you.
        • prgrgpszDictionaryBase - a pointer to a two dimensional array of pointers to null-terminated strings
        • 'nuff said

        • prgrgpszDictionaryBase - a pointer to a two dimensional array of pointers to null-terminated strings
          Funny, when I read the 'prgrgpszDictionaryBase' part in my head i heard: 'a pointer to a two dimensional array of pointers to null-terminated strings'. Then I read your description and it seemed somehow redundant. I guess that's the point right there.
  • by Rolf W. Rasmussen ( 17 ) on Sunday December 23, 2001 @08:26PM (#2745858) Homepage
    For C++, the best coding guidelines I've ever read is the proposed Boost C++ Coding Guidelines [sourceforge.net]. (The link points to an old version in the boost CVS tree. To get an updated version you'd need to join the Boost Yahoo group [yahoo.com] and get it from the "Files" section of the group.

    What I like about the guidelines is the well thought out rationales presented and its adherance to current C++ standards. After reading them, I wanted to follow the guidelines because I agreed with the rationale, rather than simply because the document said so.

  • Here's another Java style guide [javaranch.com]
  • by ChaoticCoyote ( 195677 ) on Monday December 24, 2001 @10:28AM (#2747352) Homepage

    Too many coding standards get into issues that are, quite frankly, ludicrous. If the programmers I hire can't handle slight differences in C++ brace placement, I need to find better programmers! Sheesh, I've never had problems following code because someone places the open bracket on the same line as the if, while I put mine on a subsequent line.

    Having written for publication, I've had quite some experience with the anal retentive crowd. For example, I was excoriated for having an algorithm with 1-character variable names -- the code was, however, an implementation of a specific mathematical formula, and my code precisely matched variables in the original notation. To change the names to longer "descriptive" ones would have broken the continuity between definition (in a math text) and implementation (C++). The short names were actually more descriptive and accurate!

    And then we have the "goto" wars -- I actually use a single goto in one of my books, bringing down the ire of mypoic ninnies (usually pre-degree college students) who only know that "gogot is bad" without a clue as to why they've been taught that. A rare, judicious goto can make code faster and more readable! But try telling that to fools who only parrot dogma... if a programmer can't understand the rare usefulness of a goto, they probably can't think far enough "outside the box" to be useful in the real world.

    This isn't to say that I'm against coding standards -- I'm all in favor of them! But a coding standard should by flexible in nature and open-minded where practical; the goal is readable code and ease of typing. Programmers have habits, a rhythm when they type, and so long as their code follows broad guidelines of style. I'll take a dozen good comments and a solid design document over the placement of curly brackets any day!

    • > If the programmers I hire can't handle slight differences in C++ brace placement, I need to find better programmers!

      You've never actually written code as part of a large team using source control have you? Try figuring out the diffs between the code you have just modified and the code a fellow programmer just checked in after his favorite editor just automagically realigned all the braces! Few, if any, version control tools can automagically resolve that kind of conflict for you, so you have to do it yourself, or else pull the new version to a different location, re-re-align the braces, and do the diff then. Ugh. Pick a brace (and space/tab!) style, preferably one in common use and documented, and stick with it. It's not about the readability of one person's code, it's about the compatibility of changes across time and team members.

      • You've never actually written code as part of a large team using source control have you?


        I dunno... 12 programmers at one shop, all using Source(un)Safe, working on a million-line e-banking app... seems like a "large team" to me.


        I'm concerned with clarity of algorithm -- in other words, can I understand what the program is doing? That requires good comments, not curly-bracket placement.


        You might have a point in regard to tabs/spaces, in that different people and systems have tabs set to different line positions. I've always specified hard spaces, so the code looks the same in everyone's editor and in print.


        I'm not against programming standards -- I'm against getting into insane detail. I spend far more time trying to figure out someone's algorithm (or lack thereof!) than I do worrying about their brace style.

  • We've successfully used Rogue Wave's Elements of Java Style [amazon.com] conventions on most of our projects. Of course, people will still disagree on curly braces, indentation, tabs vs. spaces, but on the whole if you have the style guide as a hardcopy book, it'll be a lot easier to settle disputes and point out the standard. And it saves a helluva lot of time for the poor sucker on the team who has to write the coding standards if he can concentrate on project-specific usage patterns and framework notes instead of detailing where curly braces go and how to write variable names.
  • I am not sure how similar C# is to Java
    but following the Microsoft recommendations in the Framework SDK might be a good idea - they seem pretty well thought out.
    In particular, check out the "Naming Guidelines" [microsoft.com] section,
    though the entire set of design guidelines is also good reading.
  • In addition to source formatting (tabs, brace placement, etc) you need to agree to a standard mechanism for functions to return status values.

    For example, if you look at the Win32 API (sorry; that's what I'm most familiar with) you will find the following mechanisms used to return error status:

    • BOOL - If FALSE, call GetLastError() to retrieve the Win32 status. Example: CreateProcess().
    • HANDLE - If INVALID_HANDLE_VALUE, call GetLastError() to retrieve the Win32 status. Example: CreateFile().
    • HANDLE - If NULL, call GetLastError() to retrieve the Win32 status. Example: CreateFileMapping().
    • DWORD - If some distinguished value (0? -1?), call GetLastError() to retrieve the Win32 status. Example: TlsAlloc().
    • DWORD - The Win32 status code. Example: RegQueryValueEx() - this API actually returns a LONG, not a DWORD, but you get the point.
    • HRESULT - The COM status code. Example: GetSiteNameFromSid().
    There are also NT kernel APIs that fail by raising exceptions. The caller must wrap the API in a try/except handler to catch the exception and retrieve the error code.

    It's not just the Win32 API that uses these mechanisms for returning status. I've seen app code that duplicates each of these. I've also seen coding errors caused by the programmer not checking for the correct condition. For example, if the app contained a function called OpenFileAndCreateMapping() that returned a HANDLE, how would you test the return value to determine if an error occurred? Test for NULL? INVALID_HANDLE_VALUE? Some other distinguished value?

    The last coding style guide I created for a large project mandated that any function that can possibly fail must return a DWORD containing the Win32 status code. This made the code easier to write, review, and maintain.
  • Whatever you do, get tool-support for it. That way, you can make non-compliant code look like it should.

    For C/C++, I use 'indent'. I don't do much Java but another poster here suggested the pretty-printer.

  • I used to be the first one in line to help develop coding standards. Now, I can't imagine wasting my time with them. I attribute it to being young and not having enough experience -- thinking that I had seen everything worth seeing. I have now seen some of the most beautiful code written in a style that most people balk at. It expresses its beauty through its amazing ideas, exquisit symetry, and ingenious compactness. Looking at an entire interpreter written as a page of APL while actually writing in C.

    I used to be a syntax bigot, but I have now seen the light (no, Perl is still ugly and unreadable with no redeaming quality, unlike the almost prefectly regular syntax and symantics of K). No coding standard can make good code, but good code could be prevented by coding standards.

    Remember, only you can help prevent segmentation faults.

    -j
  • You should definitely start with Sun's code conventions. Java is young enough that there hasn't been time for lots of divergent coding styles to take hold, and Java comes with a large run-time library which is all written in a single style.

    For example, if you want to associate some code with a Swing button click, you have to implement the interface "ActionListener" by writing a method called "actionPerformed." You are just going to confuse things if you try to enforce a different set of conventions for your own code, like "mActionPerformed" or "IActionListener".

    In my own projects, I also insist that every class and method start with a javadoc comment containing at least one descriptive sentence, and it is not allowed to be a cut-and-paste comment from some other class or method.

Prediction is very difficult, especially of the future. - Niels Bohr

Working...