Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
October 25, 2014
arrowPress Releases
October 25, 2014
PR Newswire
View All
View All     Submit Event





If you enjoy reading this site, you might also want to check out these UBM Tech sites:


 
Comment thy Code
by Vasileios Karavasilis on 07/26/14 06:21:00 pm   Featured Blogs

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.

 

[As posted on The Way of the Indie Game Developer]

It has been a while that I wanted to write this post (it was resting in my draft folder for two months now). Even though most of my articles thus far are about game design, managing or generally indie game dev advice, my main role in eNVy softworks is that of the Lead Programmer. So I think it is way past time to share a few things with all the game programmers out there.

 

If you have been programming for a while I am surely not the first one to tell you this but comments do matter. I will split this post in two parts because it is getting way larger than I expected. The first part will help you understand why you should comment on your code while in the second one I am going to give you some practical advice on how to do it in a way that is easy, practical and will not slow down your progress.

 

In this point let my clarify that this is advice applicable to all kinds of programming and not only game programming but if I find the need to include an example it will have to do with game code.

 

Let us start from the basics. What are comments? The Wikipedia definition is way more complicated than it has any right to be so let me give it to you in simpler words. Comments are a chunk of text within a computer program that the compiler ignores. The implementation differs from language to language but their functionality is always the same: a playground of characters you can use in any sense you like!

 

The most traditional way comments are used is to provide information concerning specific lines of code. You can use them to leave a note to yourself about something you want to change later on or clarifying the function of some obscure line of code.

 

Enough with the introduction! Why would you want to use comments?


Reason 1: Refactoring

 

Games tend to be some of the largest programs someone can possibly write, their length spanning from thousands to even millions of lines of codes. Large programs mean a lot of time is needed to finish them. The more you code the better you get and it is a certainty that not too late into development you will be able to improve the code you already wrote (I plan on making a full post on refactoring some time in the future).

So you go back a few months after writing the code to make it better and suddenly you have no idea what you are looking at. This does not apply to all people but most of us will forget how we implemented certain things. Never trust your memory, it will betray you, even if it has only been a few months. Having good comments all over your code will help you make refactoring a lot less painful and by far faster than you would imagine.

 

Reason 2: Re-usability


A professor of mine told us a story once. He was doing some Operating System (maybe the largest possible piece of software out there) research and came across some code an old student had once written. He tried to find some sense in the code but the complete lack of comments made it absolutely useless to him. He started cursing the student for his incompetence when he realized it was his own code after all. As I said before memory is weak and it can get you in a lot of uncomfortable circumstances.

Even thought every game is unique on its own there are certain universal elements that all games share. When making a new game you probably already have some of the elements you need to make it in an earlier game you made. Why would you code them all over again instead of just taking the old code and change what is needed to make it fit into the new game? If your old code is not properly commented you will find it really hard to even identify what you need to take from it. Revisiting the code for a game you wrote years ago and making it fit into something new is a challenge on itself, imagine how harder it gets if there are no comments around to help you out.

 

Reason 3: Teamwork

 

By now you probably know that the majority of video games are made by more than one programmer. Sometimes dozens of programmers work on the same code without even having regular contact with each other. Team programming is a really different story but the main principle behind it is dividing the program into logical chunks and assigning each one of those chunks to a different person, while some other programmers are charged with making those chunks work together. No matter the reason, other people from your team will eventually have to work with your code and, do you know what is harder than understanding a piece of code you haven't seen for years? Understanding a piece of code you have never seen before! You can make everyone's life easier by using comments. Your co-workers will have no problem understanding what you were intending to do and can utilize your code easier and more efficiently.

 

Reason 4: Debugging

 

How does commenting helps in debugging you ask? Well weirdly enough it does in a very special way. Most programmers tend to write code on the spot without planning beforehand. That means that they are not always sure where a programming session may take them. This is actually the main cause of most bugs as well. When you comment your code while you write it, you force yourself to think harder on why every line is important. If a certain line of thinking takes you off the right trail commenting while writing the code may as well lead you back on track. On the other hand if you do not change your train of thought while coding and encounter a bug it is easier to find the gap in your logic when you are reading it in a natural language (such as English) rather than in a programming language.


Those may be the main problems that comments solve but comments are not necessarily the only way to solve those problems. Sometimes comments are the best way to convey a message but sometimes simply changing the names of your functions and variables can do the job.

 

I will tell you more on how to write easy to read code and how to use comments responsibly on the next part of this article; this does not mean that my next article will necessarily be the second part of this one or that it will be delivered soon.

 

I hope you enjoyed this read, share it if you did and tell me your own views and opinions below.

If you would like to learn more on a specific subject feel free to leave a comment and I will try to help you the best I can. Have a nice day and stay focused!


Related Jobs

Red 5 Studios
Red 5 Studios — Orange County, California, United States
[10.24.14]

Graphics Programmer
Red 5 Studios
Red 5 Studios — Orange County, California, United States
[10.24.14]

Gameplay Programmer
Gearbox Software
Gearbox Software — Plano, Texas, United States
[10.24.14]

Server Programmer
Forio
Forio — San Francisco, California, United States
[10.24.14]

Web Application Developer Team Lead






Comments


Jane Castle
profile image
Comment I once saw in a code base:

/*
I do not know what this code does. The programmer who wrote it has long since left. However DO NOT
touch or modify this code, it works and horrible bugs will happen if you do. You have been warned.
*/

Mark Velthuis
profile image
At least it gives more information than these kind of comments :

//Loop through the item list and flag them all for deletion

above this kind of code :

foreach(Item item in ItemList){
item.FlagForDeleteion();
}

That's basicly like wrtiting your code twice.

Bannister Nicholas
profile image
I often write a 'template' in psudeocode, like this example, before I write any actual code logic. It helps me figure out alot of aspects of what I'm doing before wasting time actually figuring out the logic, and helps me to identify aspects of code I need to re-learn in advance.

Robert Carter
profile image
There was a comment almost identical to this within the Unreal Engine (U3, not the current one). Jumping into that engine headfirst after Epic pulled support for most platforms was a nightmare, haha

Marvin Papin
profile image
List itemList = GameObject.GetAListOfGameObjects();

Proceed();
Again();
OnceMore();
for (int i = 0; i < x; i++) {
if (it matches) DoAnything();
}

// FlagForDeletion // eventually for it to be highlight and make it more visible
// so when you have a moderately long function, You just have to read quickly
// the comments to understand what the f*** happens here. In interest of
// time.
foreach(Item item in itemList){
item.FlagForDeletion();
}






Personnaly, I comment after the lines if necessary :
obj.forces = null; // use to do a stupid thing or to avoid bugs maybe

and before it if it's to have an overview of my code :

// Reformate Data [not worth placing in another function]
ItemType[] items = bgfcxgngwng;
for (int i = 0; i < x; i++) {
items[i] = items[i-1];
items[i] *= aF***Constant;
items[i] + = anotherF***Constant; // offset toward column a
}


Aiden Eades
profile image
I once had a comment at the top of a piece of code I'd written along the lines of.

//WHY THE HELL DID I MAKE THESE ALL STATIC!
//I'm certain there was a reason behind it but I cannot
//remember for the life of me.

I was using the variables to store a bool flag that was accessed and modified from another project, without it being set to static I was setting the bool to true and it was reverting itself to false again when next checked.

Most of my comments go in after I get confused by my own code and are similar questions, I then later swap out those comments for answers to the questions.

Basically, don't comment the what, comment the why.

Why you thought it was better to write to a temp variable and then to the main variable, rather than straight up over-writing the original variable.

Why are you calling this function twice in a row?

A lot of the reasons for my terrible hacks are the extreme legacy I'm working with, the remainder are just that I'm not the greatest of coders.

nicolas mercier
profile image
I am of the opinion that good code is self-commented. Small classes, explicit variable names, parameter names and method names, nice file names, decent library structure. Just curious to see how the second half will turn up, but so far I am still not convinced. Maybe I'd agree with something like:
comment thy *bad* code.

Jonathan Jou
profile image
I agree, nicolas! There is a great place for comments, but in general comments provide clutter to the sufficiently experienced dev reading well-written code. I agree, when you can write the code clean enough that the documentation would look like a copy of the implementation, you're writing the best possible sort of code.

But when things that are too complicated to explain by name, execution flow, or organizational hierarchy are in the code, comments make sense. I like comments that explain what a highly-optimized numerical algorithm does for me without having to dig into it, and I really, really appreciate pointers in the comments to relevant reading where it could be more effectively explained. I much prefer comments over weird, convoluted attempts to explain a client-requested "fix" that's not a fix so much as it is a hacky workaround that slows down performance in general because the clients wanted it. And I know for a fact that code is unequally obvious to different people, so whenever there's doubt I would say comments are better than nothing at all.

Wyatt Epp
profile image
"Small classes, explicit variable names, parameter names and method names, nice file names, decent library structure."

My, such a lovely and idyllic world you live in! I wish I were there with you. ;)

Really, though that statement is issued with tongue firmly in cheek, I have a bit of envy for any engineer who can work with that sort of code on a daily basis. My workplace inheritance has largely consisted of networking libraries and server applications written twenty or thirty years ago with structures of up to 76(!!) members, alien abbreviations, a full-on pointer gymnasium, and actual [ab]use of the line control macros. Some of it is a little bit commented, but for the most part, any change that has side effects that go up the stack requires me spend at least a day to understand the data flow (async worker queues dispatched via lists of function pointers ensures that a day is often optimistic).

Comments above function signatures that say broadly what the next several dozen lines actually does would save me from having to spend time to read and fully understand that code and allow me to zero in on likely problem areas much faster. Comments on the "clever" things done in the name of performance would be out of this world because unravelling those knots is even worse.

In general, hygienic commenting fulfils the implicit contract that code exists for the sake of humans by saving people in the future (possibly including yourself, because you're a fallible human too) loads of time in understanding and working with anything that goes beyond rudimentary complexity. As a bonus, it'll also earn fewer plagues wished upon your houses!

Timothy Lochner
profile image
I really like that term: "Hygienic commenting".

Ian Morrison
profile image
When I'm looking for comments, I'm NOT looking for a description of what is being done unless what is being done is extremely complicated or non-obvious. In that, I'm very much on-board with the programmers who believe code should be self-documenting. However, I AM very interested in design decisions, your mental model of the problem, and broader context, and that is stuff I would really appreciate to find in your comments.

There's also a matter of being considerate to others who might use your code. YOU might think a piece of code is obvious, but it might not be so to someone unfamiliar with the code base, less experienced, or sleep deprived... or you might just be wrong about how clear it is! We're all heavily biased with regards to how easy our code is to understand, after all, we just wrote it!

Saad Khoudmi
profile image
Agreeing there. I don't think commenting for the sake of commenting is "proper".
Comments should be used wisely and not be confused with a good documentation.

If someone wants to know what a method does => Doc
If someone wants to understand how a method behaves (for further modification) then he will have to read the code, and I prefer a good written code than an extensively commented code, it just speaks to me more. However smart and brief comments in wise spots are always welcome to ease the process of understanding.

This guy explains it well
http://blog.codinghorror.com/coding-without-comments/

Bob Philhower
profile image
I agree with Ian. I was saved by such comments just a few days ago in a very old script.

The code itself was extremely simple (very little control flow) and short. And I knew exactly WHAT it did. I thought I remembered WHY I had included a particular operation that seemed to be causing problems years later. (and why it was no longer needed)

But, a comment let me know of a more subtle reason for that operation and led me to a code change that fixed my problem without introducing another bug.

Bannister Nicholas
profile image
is it just me? or did you just write:

Don't comment unless its not obviously clear,

but you should comment even if its obvious.

nicolas mercier
profile image
@Ian: documentation does not need to be in comments. If you are interested in design decisions and architecture, other forms of ducomentation could be more suitable; like a formatted Wiki page.
Comments are just plain text embedded in the source code and as such are quite limited; how many of you have seen ASCII art (programmer art probably :) ) in the comments to draw a diagram or a flow chart?

Yes to documentation, and I agree with Jonathan, yes to comments describing overly complex algorithms (maths is not always trivial, even though the resulting formula can be easily implemented), and probably, yes to comments if you think the code is bad :)
But embedding real documentation in comments, I am not sure I see a big benefit.

@Saad: I read the thread sequentially, I just came across your post, yes that's what I meant :)

Marvin Papin
profile image
@Bannister

DoSomeStuff(); // DoSomeStuff ;)


////////////////////////////// a bit less obvious

for (int i = 0; i < itemsVal.length; i++) itemsVal[i] += 1; // increment items ;)

Evan Combs
profile image
I agree Nicolas. I don't understand how people can code any other way.

What I always do is put a short explanation of what the function does above the function just to give the reader some context. After that I try to make sure everything is named in a way that is obvious. Other than that I will comment when I put something in to fix/avoid a bug, or explaining what a math equation does.

As well proper organization can go a long way. I always put related functions next to each other, and put extra spaces between unrelated functions.

Stephen Coy
profile image
Self-documenting code can only ever document what the code does, not what it was intended to do. The differences between the two are bugs.

Comments should cover the intent of the code. They should cover any assumptions made and shortcuts taken based on those assumptions. If a class needs to be used in conjunction with other classes this should be covered in the comments. If you're doing something tricky, describe the algorithm you're using. Maybe even reference a book or web site which details the algorithm.

Good comments make code more readable, debugable, reusable and maintainable.

nicolas mercier
profile image
I sort of disagree. Self documenting code indicates what it is meant to do as well, a function that is called SquareRoot and returns somthing else is still self documented. If classes need to be used together, it can be documented by having one of the classes a private class nested in the other or something like that, or if polymorphism is involved, you can force this dependency by passing one as a parameter to the other in the constructor... I do think here are ways to ducument that. Shortcuts as well. Just not all the time.

Design decisions can also be described outside the source code, comments don't need to be your only source of documentation.

I am not saying no comment is useful, but there are few cases where I thought it was the best tool for documenting.

Thomas Happ
profile image
More and more I find myself having to go through the perforce repository to figure out whether there really was a purpose to some bugged-out uncommented code, or if it was just a typo. So always comment your checkins, if not your code!

Wes Jurica
profile image
I tend to agree with some of the people above. For most cases, I don't find comments very useful if the code is well written.

The two exceptions off the top of my head are:

1. Mathematical formulas. Take the Pacejka formula http://upload.wikimedia.org/math/a/e/f/aefbc14ce93ec5e167385c6962
d1bb91.png for instance. Having each part of the code implementation commented to show which part of the formula it corresponds too is very helpful because the formula in mathematical notation looks very different from the code version.

2. When making additions to someone else's code (of which you are not a contributor). For example, I modify nearly everything I get off the Unity Asset Store. When I got Tasharen's NGUI package it was no different. I had made a ton of additions and some of those were things that were glaring omissions as far as I was concerned.

A few months later I went back to the project for some maintenance, updated NGUI and copied in all my changes to the new version. I got an error saying a variable was missing and made a post on the NGUI forums asking why the author removed such a basic feature. He replied that he had never had such a feature in the project and that I must have added it. Sure enough... How embarrassing.

Charles Palmer
profile image
The modern answer to most of those problems is actually good automated testing.

Making code unit testable goes a long way to making it reusable, makes refactoring a doddle and is self documenting. Plus you get a computer checking them all for consistency with each change. All of which aids teamwork.

Comments definitely have their place, particularly if you are auto-generating documentation but they suffer from being open to interpretation, no coupling with code so they can get out of date easily and when the comments are bad just add clutter.

These days I prefer my code to be readable, use good IDEs and comment only when the code is otherwise dense and obscure.


none
 
Comment: