Skip to main content
GameDev.net gamedev.net
🔒 Locked

Commenting and Documenting code

Started by nivlekio Aug 23, 2008 at 10:28 PM 25 replies 4.5k views
Original Post
nivlekio
nivlekio
Hey all i am at the point where i want my code to become a bit more professional and tidy, i really need to kick the messy cow boy coding. I'm looking for pointers like for example what type information should and should't i include in the documents and how i should go about documenting my code and files as well. Thanks for the help in advance.
Telastyn
Telastyn
I offer perhaps poor advice, since I don't comment my code much at all.


If you name things well and consistently, comments should be few and far between. At that point, comments are needed where things deviate from the consistent naming or program flow. Places where (due to imperfect design or requirements) the code is a little weird or ugly or plain unreadable. If you make a non-trivial bug fix, comment the place with the bug/ticket number and a quick summary of the original bug (so someone maintaining the code doesn't re-introduce it).
Sneftel
Sneftel
I'm in the "write self-commenting code, and only comment where the code doesn't make entire sense" camp, with one huge caveat: All code makes entire sense five seconds after you write it. Determine (by carefully reading over code you wrote a year ago, or better yet, by doing a code review) how much you can trust yourself to objectively decide whether code is confusing or not, and overcomment (or not) accordingly.
niteice
niteice
It's always nice to give a general overview of a function no matter how self-documenting the actual code may be. Given a description of a function and a clear naming and stylistic convention, comments within a function should not be overly necessary.

Of course, the above posts are good advice as well.
bitshifter
bitshifter
A good description is nice to have, but don't get too fancy.
Changes in the code later on might not jive with the old comments.
This means when you make changes to your code, the comments must also be updated.
So keep them short and sweet.
Telastyn
Telastyn
Quote:
Original post by bitshifter
A good description is nice to have, but don't get too fancy.
Changes in the code later on might not jive with the old comments.
This means when you make changes to your code, the comments must also be updated.
So keep them short and sweet.


I've seen more times where the comments were misleading/incorrect than I've seen a description be useful. I question even 'a good description is nice to have'. The best comments are often not what or how, but why.

If your method is so obtuse as to need a description, it's a good indicator that it needs broken down into 2+ methods. Not commented for clarity.

(IMO)
Wyrframe
Wyrframe
Under Java and C++...

I use the "my wife" rule. If my wife (an English and Drama teacher) couldn't have told me what the function does by its name and argument list alone, I either rename it so she can, or write a one-line comment that she would understand. If she couldn't have told me what a loop iterates over, I either rename the iterator variable or add a one-line explanation. If she couldn't have told me what a given line does, I break it up into separate lines until either she could, or until I can say what it does with a one-line comment.

The assumption is; if the source isn't readable english, it probably isn't readable source either. Mind, that is all only for Java and C++.

Under Erlang, Objective Caml, and Prolog, I document each function, functor, object, or rule with up to a paragraph or two, but don't comment individual lines because in those languages, 95% of functions/rules are one-liners.

Under Smalltalk, I document each class with anywhere from a paragraph to a novel, and each function with up to a single paragraph. If the source of a function needs deeper explanation, then I could either break that function up into smaller functions, or leverage functionality from other objects instead.
RIP GameDev.net: launched 2 unusably-broken forum engines in as many years, and now has ceased operating as a forum at all, happy to remain naught but an advertising platform with an attached social media presense, headed by a staff who by their own admission have no idea what their userbase wants or expects.Here's to the good times; shame they exist in the past.
nivlekio
nivlekio
Ok cool thnaks for the advice guys :), I like your approach Wyrframe.

I recently started commenting my class fucntions in the .h like this

	/*-------	Function name:	-	RegisterWindow	Overloaded:	-	Yes	Purpose of function:	-	To register the new window		RegisterWindow(char *prm_szClassName) - If the defualt setting are required												then this function should be called		RegisterWindow(CONST WNDCLASSEX* prm_Wcx) - Call this function to set the windows													classes ex structure	Parameters: 	-	Paramter 1 (prm_szClassName) -	Pass in the name of the classes ex structure	-	Paramter 1 (prm_Wcx) -	Pass in the class ex structure	Returns: 	-	If the window is registered then return true else return false.	Notes:		-	None	Tested:	-	Yes	Minimum Spcifications:	-	Windows 95 and 5.1	Updates:(all updates must be kept in chronological order!!)	Date Changed:	-	Modification:	-	Person who updated it:	-	-------*/	virtual BOOL RegisterWindow(char *prm_szClassName);	virtual BOOL RegisterWindow(CONST WNDCLASSEX* prm_Wcx);	////	////


Is this alrite or is it too much?


If it is too much shall i use that style as documenting? then ill just put simple comments (like a line or two) above the function declarations, and if the reader does not fully understand the comment they can always look at the document for further information.
Sneftel
Sneftel
It's fine, but you may as well use a standardized commenting style, such as Doxygen, even if you don't use a documentation generator.

Also, changelogs do NOT belong in comments. They belong in source control.
CRACK123
CRACK123
In the current game we are making in our company we adhere to more meaningful function and variables names and don't write unnecessarily complicated for no reason rather than writing 10 lines of comment as code gets frequently updated.

Although I did comment major areas of the code, the only reason to do that was so that someone not equally experienced( a complete newbie - yeah we get quite a few newbies in our country who think they know everything ) would be able to figure it out in no time.


The more applications I write, more I find out how less I know
ractoc
ractoc
I usually give a short explanation above each class / method. This is especially important for public methods since they will be called by other developers (most likely).

Besides the general class / method comments I comment each boolean statement containing more then 2-3 parts.

The commenting of class / method / public constant is very important in Java, especially if you use JavaDoc comments. With these you can then generate a HTML API documentation which other developers can use to get to grips with your code.

When working witl other developers on the same codebase I also try and write method level comments for each private method, but this is of less importance.
Kylotan
Kylotan
Personally I think very little code is as self-documenting as people think it is. Often there's just too many classes and subsystems in a large project for anybody to look at a random function for the first time and understand fully what is going on. So comments are important.

I don't see much value to the type of comments you've got there, ie. massive blocks of data at the top of a function. It seems too formal and says too much. If you had 30 lines of preamble comments for every 1 line inlined-function, your code would be barely more usable than if you had no comments at all.

Instead, I comment about the whats and whys of my code, leaving out the how. Never just rehash your algorithm in English, but explain what each few lines are trying to achieve, why you pass some less obvious parameters, what is going on behind the scenes of any important calls, etc.
BreathOfLife
BreathOfLife
I find that, as said before, well thought out variable/function names just sort of, explain stuff clearly. For anything that has alot of branches and/or series of steps, i use pseudo code of sorts, and just leave it in, it becomes the comments and explains things without too much added effort.
hydroo
hydroo
Quote:
Original post by Sneftel
I'm in the "write self-commenting code, and only comment where the code doesn't make entire sense" camp, with one huge caveat: All code makes entire sense five seconds after you write it. Determine (by carefully reading over code you wrote a year ago, or better yet, by doing a code review) how much you can trust yourself to objectively decide whether code is confusing or not, and overcomment (or not) accordingly.


qft

once you've developed the ability to distinguish whether your code is intuitive or not you'll be fine.

+ Interfaces that will be accessed by others have to be documented in greater detail.
metalman666
metalman666

I can say only one thing. Commenting your code sure helps.

Commenting my codes gave me break at a very big company. When appearing for the test they asked me to make a arcade game. Yeah they asked me to make a full game(given me 4 hours). I thought it would be better if i can properly document the code also. In the discussions round they said that it was my proper documentation and comments that earned me extra points.

But excessive commenting is also not desired.
eg.



will do the trick.

So, put it simply Commenting and Documenting your code sure helps.
stimarco
stimarco

Code should be self-documenting as far as possible.

This is harder with OO languages, but that's due to flaws in the languages' design as much as anything else. (Language designers need to think about all aspects of development, including the necessary ecosystem of tools that surround their language. Anyone who thinks that merely designing the language itself is enough needs to be taken out and shot.)

If you have a particularly obscure-looking line of code, and refactoring it or rewriting aren't viable options -- perhaps the language doesn't let you express a particular algorithm elegantly; it does happen -- then you should comment that line and explain why it looks like that.

Comments should generally be limited to brief function purpose descriptions. That's "purpose", not "implementation": Nobody cares *how* it works because that should be obvious from the code itself.

You need to document why the function is necessary, what it needs passed to it, and what the expected limits are on parameter values if the function itself cannot clean them or sanity-check them itself. (The latter should, wherever possible, be enforced by the function itself; do NOT rely on programmers to remember such details! If it's possible to clean up 'dirty' parameters, do so and document the default settings used when this happens.)

A Class (OOP) or Library / Module (Structured / whatever) should be fully documented as if you were selling it to a third party. Explain what the Class / Library / Module does, how it should be used, and any caveats or limitations which should be considered by the library's user. Coupled with the individual docs for the (exported) functions, this information should be enough to let _anyone_ use the library without having to phone you up for info.

Using an automated documentation tool is a huge bonus. Some languages explicitly support such tools -- e.g. Java and the .NET / Mono languages -- although back-end support can be lacking. For older languages, such as C and C++, consider Doxygen or an equivalent.


If the above is too much to read, just remember the two Golden Rules:

1. Comments document purpose, not implementation.
2. Your source code should be readable enough to document the implementation.


Sean Timarco Baggaley (Est. 1971.)Warning: May contain bollocks.
stonemetal
stonemetal
Documentation should tell why something is happening(or not happening) not what the code is doing. I get what the code is doing by looking at the code(if good names are used.)

//Get player location.
Map.GetLocation(Player);

VS

//Pulling player location for visibility check.
Map.GetLocation(Player);

Now both of those are stupid because they are probably obvious by context, but the second makes more sense because I know why that line of code is there(and what it is doing because of the clear naming). The second reason to document something is to explain why you aren't doing something.

//returns true if ai should fire weapon.
// doesn't do visibility check because everything we consider comes from a list that has already been through visibility
//determination step over in make_list_of_things_to_shoot.
bool AI_Should_shoot()
hydroo
hydroo
the previous post reminds me of: please consider using doxygen.
(because you can generate a neat html/tex-documentation ... really useful!)
gosh
gosh
Quote:
Original post by nivlekio
Is this alrite or is it too much?


Too much. Commenting code is very good, you should always code like you do it for another person. But commenting to much will just bloat the code. Describe the functionality in order to make it easy to understand the code.

Also try to write code so it is possible to just focus on the code.
jpetrie
jpetrie
Quote:
Original post by nivlekio
Ok cool thnaks for the advice guys :), I like your approach Wyrframe.

I recently started commenting my class fucntions in the .h like this

*** Source Snippet Removed ***

Is this alrite or is it too much?


I think it's too much. There's too much useless information in the comment that can very easily become out of sync with the actual function: the function name, the 'notes' section (why is this different from the description of purpose?), the 'tested' flag (you should be able to determine this from your test reports), the minimum specifications (functions are way too low level a place for this), the changelog information (we have source control with blame functionality for a reason). All of this equates to the likelyhood of either: desynchronizing your comments, at which point they are dangerous, and/or spending more time maintaining the comment's pointless details rather than the code.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.