Best practice for C++ function commenting

1337 picture 1337 · Feb 4, 2010 · Viewed 76.6k times · Source

Is there an accepted best practice for commenting functions? I only know of the doxygen style but it is not officially supported by C++ like Javadocs is for Java so just wondering what is best.

Answer

GManNickG picture GManNickG · Feb 4, 2010

There only general thing most people will agree with is that comments should say "why", not "what". Other than that, guidelines depend on the coding standards at your place of work.

Personally, I hate doxygen and the like, because it contradicts the first thing I said. The "documentation", if it can be called that, is just a prettified header file. And the cost? Nearly duplicated code, obtrusive comments (seriously, it doubles the height of everything), and just a pain.

Your code should be self-documenting: use descriptive names, factor everything into well-defined tasks, etc. The only comments should be things that may need clarification.

For example, an excerpt from a network socket class I wrote:

const bool socket_connected(void) const;

You already know what this function does; I don't need to explain it. Do I really need to add a big chunk of comment explaining that it returns a boolean (duh) that will indicate of the socket is connected (duh)? No. doxygen is just going to take my header and add some fancy style-sheet to it.

Here's an example where a quick note may be useful (making this class up):

struct fancy_pants
{
    // doesn't transfer ownship, ensure foo stays alive
    fancy_pants(foo&);
};

Now it's clear I need to make sure the foo I pass it doesn't go out of scope. This didn't require the uglification of my code. If I'm going to write documentation, it should be written by me, describing rationale, intended usage, "gotcha"'s , examples, etc. Like Boost.

That said, all my headers have a copyright block on the top. I find this is a fantastic place to write a tiny bit of info about the class. For example, is_same.hpp:

/*-------------------------------------------------------
                    <copyright notice>

Determine if two types are the same. Example:

template <typename T, typename U>
void do_something(const T&, const U&, bool flag);

template <typename T, typename U>
void do_something(const T& t, const U& u)
{
    do_something(t, u, is_same<T,U>::value);
}

---------------------------------------------------------*/

It gives a quick demo at a glance. Anything more, like what I said above, is in a written documentation file.

But you see, I get to make up my code standards for the most part. At companies, you usually have to follow their standard anyway.