Comments and Spacination

This will probably be the last article on style for a while, though there will be more at some point. I’m going to talk about two other aspects of code formatting that are almost as important to me as variable naming: comments and the way you space/tab your code. The latter will now be referred to as “spacination”, although Chrome tells me it’s not a real word. 😦

With the exception of small programs that have run-once use cases, e.g. Project Euler entries, I try to comment all my code. I’ve often heard “if it was hard to write, it should be hard to understand” as justification for leaving code unexplained, however this is in my opinion just shooting yourself in the foot. What if you come back later and need to change something? I always treat my code as if someone else is going to read/use/modify it at some point in time, regardless if that someone is me or not.

I’ve also gotten into the habit of writing Doxygen-compliant comments on all class, method and variable definitions, especially on larger projects. Doxygen is kinda like JavaDoc, in that it generates documentation from comments written directly in the source. It also provides inheritance trees, lists of constructors, members and pretty much everything you’d expect from such a tool. The rules are pretty flexible for creating these types of comments, as you can use either /// or /**  */ to catch the attention of the Doxygen tool. Some examples:

Regular comments, such as the ones describing the internals of a method, are of course the regular double slash. Even if you don’t use Doxygen, it’s still good practice to comment things. I find it makes for better code in the long run, at least for me.

The next one I’m a bit pickier about. I’m not sure why as I’m not really a neat person in everyday life, but when I write and read code my brain requires it to be spaced out in a very specific way. Maybe it’s because I learned Python first, where indentation was part of the syntax. Either way, I’m very picky about making things line up. There has to be clear levels of indentation, in tabsteps from the left hand margin. I also prefer to have curly braces ({}) on their own line, as opposed to at the end of a function or class definition. Example: 

Again, like the variable names, these are just personal preferences and not hard fast rules. I just find these conventions improve the quality and appearance of the code.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: