Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

For some time now, I've been unable to settle on a coding standard and use it concistently between projects. When starting a new project, I tend to change some things around (add a space there, remove a space there, add a line break there, an extra indent there, change naming conventions, etc.).

So I figured that I might provide a piece of sample code, in C++, and ask you to rewrite it to fit your standard of coding. Inspiration is always good, I say. ^^ So here goes:

#ifndef _DERIVED_CLASS_H__
#define _DERIVED_CLASS_H__

/**
 * This is an example file used for sampling code layout.
 *
 * @author Firstname Surname
 */



#include <stdio>
#include <string>
#include <list>
#include "BaseClass.h"
#include "Stuff.h"



/**
 * The DerivedClass is completely useless. It represents uselessness in all its
 * entirety.
 */
class DerivedClass : public BaseClass {

    ////////////////////////////////////////////////////////////
    //   CONSTRUCTORS / DESTRUCTORS
    ////////////////////////////////////////////////////////////

public:

    /**
     * Constructs a useless object with default settings.
     *
     * @param value
     *        Is never used.
     * @throws Exception
     *         If something goes awry.
     */
    DerivedClass (const int value)
     : uselessSize_ (0) {}

    /**
     * Constructs a copy of a given useless object.
     * 
     * @param object
     *        Object to copy.
     * @throws OutOfMemoryException
     *         If necessary data cannot be allocated.
     */
    DerivedClass (const DerivedClass& object) {}

    /**
     * Destroys this useless object.
     */
    ~DerivedClass ();



    ////////////////////////////////////////////////////////////
    //   PUBLIC METHODS
    ////////////////////////////////////////////////////////////

public:

    /**
     * Clones a given useless object.
     *
     * @param object
     *        Object to copy.
     * @return This useless object.
     */
    DerivedClass& operator= (const DerivedClass& object) {
        stuff_ = object.stuff_;
        uselessSize_ = object.uselessSize_;        
    }

    /**
     * Does absolutely nothing.
     *
     * @param useless
     *        Pointer to useless data.
     */
    void doNothing (const int* useless) {
        if (useless == NULL) {
            return;
        }
        else {
            int womba = *useless;

            switch (womba) {
                case 0:
                    cout << "This is output 0";
                    break;

                case 1:
                    cout << "This is output 1";
                    break;

                case 2:
                    cout << "This is output 2";
                    break;

                default:
                    cout << "This is default output";
                    break;
            }
        }
    }

    /**
     * Does even less.
     */
    void doEvenLess () {
        int mySecret = getSecret ();
        int gather = 0;
        for (int i = 0; i < mySecret; i++) {
            gather += 2;
        }
    }



    ////////////////////////////////////////////////////////////
    //   PRIVATE METHODS
    ////////////////////////////////////////////////////////////

private:

    /**
     * Gets the secret value of this useless object.
     *
     * @return A secret value.
     */
    int getSecret () const {
        if ((RANDOM == 42) && (stuff_.size() > 0) || (1000000000000000000 > 0)
            && true) {

            return 420;
        }
        else if (RANDOM == -1) {
            return ((5 * 2) + (4 - 1)) / 2;
        }

        int timer = 100;
        bool stopThisMadness = false;
        while (!stopThisMadness) {
            do {
                timer--;
            } while (timer > 0);

            stopThisMadness = true;
        }
    }



    ////////////////////////////////////////////////////////////
    //   FIELDS
    ////////////////////////////////////////////////////////////

private:

    /**
     * Don't know what this is used for.
     */
    static const int RANDOM = 42;

    /**
     * List of lists of stuff.
     */
    std::list <Stuff> stuff_;

    /**
     * Specifies the size of this object's uselessness.
     */
    size_t uselessSize_;

};



#endif
share|improve this question

closed as not constructive by MichaelT, gnat, Martijn Pieters, Giorgio, MainMa Mar 15 '13 at 19:08

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
I fixed the formatting, added the [coding-standards] and [coding-style] tags, and removed your meta-discussion. If you want to discuss the site itself, please use the meta-discussion site. –  user8 Sep 16 '10 at 23:23
    
Ah, sorry. I assumed this site used the same tags as Stack Overflow. Thanks for fixing it. –  gablin Sep 17 '10 at 9:02
4  
You should remove the _ from the start of the include guards; names like that are reserved. –  Mike Seymour Sep 27 '10 at 18:08
    
@gablin: there's so much useless comments I've thrown up before reaching the destructor. I prefer (c)lean code ;) –  Matthieu M. Feb 17 '11 at 19:12
1  
Your guards are reserved. _<Capitol Letter> at the beginning is reserved. Also double _ at the end is reserved. stackoverflow.com/questions/228783/… –  Loki Astari Feb 21 '11 at 18:39
show 3 more comments

9 Answers 9

  • I don't write useless meta comments which describe parts of my code.
  • Most comments are simply single line comments, so that I can comment out large blocks of code with /* and */ for testing.
  • Braces are always on their own line because I find the code easier to read that way.
  • I always have at most (if any) one public, private and protected section.
  • I don't waste time in comments with formatting like "This is a parameter name coming up!"
  • I don't put comments just to have one like on a destructor, I know it's a destructor, so does everyone else, no extra clarification needed.
  • I don't put separators into my code with big comment blocks.
  • If I have a multi line comment that continues I will put a space before the second comment line starts after the //.
  • I do add comments on parts of code that are not immediately obvious what it does. Such as loops that do something.

.

#pragma once  

#include <stdio>
#include <string>
#include <list>

#include "BaseClass.h"
#include "Stuff.h"


//The DerivedClass is completely useless. It represents uselessness in 
// all its entirety.
class DerivedClass : public BaseClass 
{
public:

    //Constructs a useless object with default value.
    DerivedClass (const int value)
     : uselessSize_ (0) 
    {
    }

    DerivedClass (const DerivedClass& object) 
    {
    }

    virtual ~DerivedClass();

    //Clones a given useless object and returns itself
    // object specifies the object to clone from
    const DerivedClass& operator= (const DerivedClass& object) 
    {
        stuff_ = object.stuff_;
        uselessSize_ = object.uselessSize_;
        return *this;
    }

    //Does absolutely nothing
    // useless is a pointer to some useless int
    void doNothing (const int *useless) 
    {
        if (useless == NULL) 
        {
            return;
        }
        else 
        {
            int womba = *useless;

            switch (womba) 
            {
                case 0:
                    cout << "This is output 0";
                    break;

                case 1:
                    cout << "This is output 1";
                    break;

                case 2:
                    cout << "This is output 2";
                    break;

                default:
                    cout << "This is default output";
                    break;
            }
        }
    }

    //Does even less.
    void doEvenLess () 
    {
        int mySecret = getSecret ();
        int gather = 0;
        for (int i = 0; i < mySecret; i++) 
        {
            gather += 2;
        }
    }

private:

    //Gets the secret value of this useless object.
    int getSecret() const 
    {
        if ((RANDOM == 42) 
          && (stuff_.size() > 0) 
          || (1000000000000000000 > 0)
          && true) 
        {//Continue looping until some condition is met

            return 420;
        }
        else if (RANDOM == -1) 
        {
            return ((5 * 2) + (4 - 1)) / 2;
        }

        int timer = 100;
        bool stopThisMadness = false;
        while (!stopThisMadness) 
        {
            do 
            {
                timer--;
            } while (timer > 0);

            stopThisMadness = true;
        }
    }

    static const int RANDOM = 42;
    std::list <Stuff> stuff_;
    size_t uselessSize_;
};
share|improve this answer
    
I [try to remember to] use #if 0 and #endif. –  muntoo May 20 '11 at 4:20
add comment

Realize that since there is zero consensus on what beautiful code looks like, if you ever want to enjoy sharing your code with other developers you need to compromise and settle on something. I strongly urge you to follow Google's C++ style guide. Feel free to disagree with any individual items, but do follow it.

It is far better to say "I code in style X -- here is the document explaining the style" than have a random and sometimes inconsistent list of opinions.

share|improve this answer
    
Nice, I'll take a look at it! Thanks! –  gablin Feb 21 '11 at 21:19
add comment
  • _DERIVED_CLASS_H__ is a reserved identifier—in three(!) different ways (leading underscore at global scope, leading underscore followed by uppercase letter, adjacent underscores). I generate GUIDs (either the easy manual form or more formal auto-generated form) for include guards.

  • Always use struct to declare classes. Public inheritance is much more common (at least for me) than protected or private, and I like seeing the public interface first. In template meta-programming, you might have 10-20 very short classes. Removing all those publics adds up to significant readability improvements and slightly more consistency when declaring classes.

  • Zealous comment blocks (especially offset with dedicated lines) are just noise. I do group public ctors and dtor together, however, as well as related methods and then operators. I tend not to intersperse accessibility specifiers, having just one each of public, protected, and private; in that order.

  • Functions (and ctors) declarations and calls have no space before the opening paren. But an object constructed with parameters does have a space, since it's not a function:

    T var (param, eters);
    Ctor(int n) : Base(n), data (n) {}
    
  • Anything I consider obvious from a name does not need a comment. ("DoNothing" is obvious enough to me.)

  • Template argument and parameter lists have no space before the angle bracket, just as for function calls and declarations.

share|improve this answer
    
+1, tight code means more code on the screen (though there's a limit to understandability :p) –  Matthieu M. Feb 17 '11 at 19:15
3  
I use struct to denote a bundle of data, and class with a few public keywords to denote something that makes sense in itself. –  David Thornley Feb 21 '11 at 21:17
    
Adjacent underscores are fine so long as they do not start the identifier, IIRC. (And for the record I agree with you and disagree with @David on the struct vs. class thing) –  Billy ONeal Mar 31 '11 at 16:25
    
@Billy ONeal: Adjacent underscores are not fine. See the Standard, 17.4.3.1.2: "Each name that contains a double underscore (__) or begins with an underscore followed by an upper-case letter (3.11) is reserved to the implementation for any use." –  David Thornley Mar 31 '11 at 16:29
    
@David: I stand corrected :) –  Billy ONeal Mar 31 '11 at 16:31
add comment

I separate in a header (.hpp) and a code (.cpp) file, the documention is in the code file.

/**
 * This is an example file used for sampling code layout.
 *
 * @author Firstname Surname
 */

#ifndef DERIVED_CLASS_H
#define DERIVED_CLASS_H

#include <stdio>
#include <string>
#include <list>

#include "BaseClass.h"
#include "Stuff.h"

/**
 * The DerivedClass is completely useless.
 * It represents uselessness in all its entirety.
 */
class DerivedClass : public BaseClass
{
public:
    DerivedClass(const int value);
    ItemList(const DerivedClass & object);
    ~ItemList();

    DerivedClass& operator=(const DerivedClass & object);

    void doNothing(const int * useless);
    void doEvenLess();

private:
    int getSecret () const;

    static const int RANDOM = 42; /**< Don't know what this is used for. */
    std::list <Stuff> _stuff;     /**< This is a list of lists of stuff. */
    size_t _uselessSize;          /**< Specifies the size of this object's uselessness. */
};

#endif
share|improve this answer
    
Yeah, I do that too normally, but this time I combined to header file and the source file to make the example a bit smaller. –  gablin Sep 17 '10 at 9:08
    
Similar to my style. The only significant difference is that I add javadoc-style comments to all methods as I run the whole thing through Doxygen to generate autodocs. –  Ant Feb 17 '11 at 15:49
    
@Ant: Same here, but I add the documentation in the source code to keep my header file clean. Getting the documentation in the header file can then simply be done by hovering the method name... :-) –  Tom Wijsman Feb 17 '11 at 16:28
add comment

I have a perhaps more compact style:

  • My headers get listed first, followed by standard headers.
  • I believe strongly in naming conventions that are self-documenting.
  • I use comments sparingly, and only for documentation purposes, and most would probably call my code "undocumented." It's documented, I just don't use Doxygen like everyone else.
  • My indentation style is compact, and label-like syntax is always exdented.
  • I do, in fact, use tabs, but under a single strict rule: only for indentation,

... And so on.

I use a variation of the Google C++ Vim indent plugin to help me enforce it.

#ifndef DERIVED_CLASS_H
#define DERIVED_CLASS_H

#include "BaseClass.h"
#include "Stuff.h"

#include <stdio>
#include <string>
#include <list>

/** A class that has no purpose, no value, and no use. Like me. */

class CompletelyUseless : public BaseClass {
private:

    static const int RANDOM = 42;

    std::list <Stuff> stuff_;

    size_t size_;

public:
    CompletelyUseless (const int value)
        : size_ (0) {}

    CompletelyUseless (const CompletelyUseless& object) {}

    ~CompletelyUseless ();

public:
    CompletelyUseless& operator= (const CompletelyUseless& object) {
        stuff_ = object.stuff_;
        uselessSize_ = object.uselessSize_;        
    }

    void doAbsolutelyNothing (const int& useless) {
        switch (useless) {
        case 0:
            cout << "This is output 0";
            break;

        case 1:
            cout << "This is output 1";
            break;

        case 2:
            cout << "This is output 2";
            break;

        default:
            cout << "This is default output";
            break;
        }
    }

    void doEvenLess () {
        int mySecret = genSecretValue ();
        int gather = 0;
        for (int i = 0; i < mySecret; i++) {
            gather += 2;
        }
    }

protected:
    int genSecretValue () const {
        if ((RANDOM == 42) && (stuff_.size() > 0) 
                || (1000000000000000000 > 0)
                && true) {
            return 420;
        } else if (RANDOM == -1) {
            return ((5 * 2) + (4 - 1)) / 2;
        }

        int timer = 100;
        bool stopThisMadness = false;

        while (!stopThisMadness) {
            do {
                timer--;
            } while (timer > 0);

            stopThisMadness = true;
        }
    }
};

#endif//DERIVED_CLASS_H
/* vim:ci:sw=4 ts=4 sws=4 */
share|improve this answer
    
"My headers get listed first, followed by standard headers." --> no PCH then ? –  Matthieu M. Feb 17 '11 at 19:15
    
@Matthieu M.: No. It was never an issue for me. That, and my build process makes little room for it. –  greyfade Feb 17 '11 at 21:37
add comment

Personally I like:

Bar MyClass::foo(Bar _input){
    if( _input.next() != NULL ){
        string functionVar = "something";
        _input.print( functionVar );

        return m_MemberVariable + _input;
    }
    else{
        return m_MemberVariable;
    }
}

But I will use whatever standards my team agrees to use. It's better that way for everybody. If it really bothers you that much you can grab a code beautifier which runs during check-out and check-in to change the format to match your styles without violating company guildelines.

share|improve this answer
add comment

My code would look exactly like yours!

but then, that's not unusual as my first coding standard (that rules all others) is that your code must be consistent, and if I've already got code formatted like yours, then I keep that formatting.

TBH, anything else is just fluff and pretty trivial. I get to work with lots of different codebases, quite a lot of them are wildly different so I've become used to seeing what the code does without needing to have it prettily laid out. So in many respects, coding standards themselves are an irrelevance (as long as the code is internally consistent).

share|improve this answer
add comment

As Chris Smith already pointed out, there is no standard on this matter. I'd like to expand this a bit more:

A coding standard is an agreement between people. It is always external to a programmer. Therefore,

it's rather meaningless to have an agreement between you and yourself :)

As far as your code stays readable and maintainable, any style is okay — there are automatic formatting tools after all.

And of course, when these conventions are among the requirements (by a boss, a team, a customer, whoever), a must is a must.

share|improve this answer
add comment

In my standards:

Layout

  • Allman (block) bracing style as with many of the others here. Far more readable.

Content

  • Implementation classes, as DerivedClass is, are rarely inlined. This particular one certainly would not be, unless it were actually inlined in a compilation unit and never even got to be defined in a header. Instead in the header you declare a "factory" function to create a pointer to a BaseClass, which is then implemented in DerivedClass.cpp to return a pointer to a DerivedClass.

  • Classes in a hierarchy are never assignable. If they are copyable it must be through a clone function. This way you never slice.

  • Keep virtual in function names even if they are overrides of functions in the base class, with a comment that they are.

  • Any constructor that takes a single parameter should be explicit

  • Stuff probably should be forwardly-declared rather than included as a header.

One of my assumptions with a class like this is what will be using it. In the case of most derived classes, nothing is accessing it directly, and all access it through the base class and the one "factory" method that creates it.

Semantics of a class, i.e. how it will be used, play a major part in the coding standard, such that in the case of a class that is accessed in this way, even if we split to header and implementation, firstly the header appears in the source folder, and secondly it does not need to forwardly-declare but can include headers direct.

share|improve this answer
    
But don't you think it's too rigid? –  vines Jul 12 '11 at 12:28
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.