Commenting your code
By rickvdbosch
- 2 minutes read - 274 wordsThere are several ways to comment your code. There’s the style where you place comments on the same line as the code. This might get less readable, because there’s some horizontal scrolling involved when your statements get longer. An example:
string s; //Declare string
s = e.Message; //Assign exception message to string s
Another way to place comments in your code is to place every comment on its own line. This is less readable when you get long methods, because your methods will get twice as long because of the comments! An example:
//Declare string
string s;
//Assign exception message to string s
s = e.Message;
My thoughts about commenting are: don’t. I think naming should be so readable that every line of code makes sense. Use the C# ’three-slashes-comment-block’ to explain what a method does which parameters it takes and, if necessary, what it returns. The above given code example would look like this:
string exceptionMessage;
exceptionMessage = exception.Message;
This piece of code doesn’t really move mountains, so it’s kind of hard to find a good descriptive piece of text for it. I’ll leave that up to your own imagination ;).
You see that, by naming the Exception exception
instead of e
, it is instantly much clearer what it contains. The string is now called exceptionMessage
which leaves very little place for argument as to what this variable would contain. Therefore the line where the exception message is assigned to the string doesn’t need any comments. This eliminates all comment within your code, except for maybe the occasional exotic function you call, where you need to specify why or how you’re calling it…