home comics writing pictures archive about

2016-04-09 - Why Comment

Commenting code is one of those things that seems simple at first but turns out to be rather complicated. Write too few comments and it's hard for people to understand the code. Write too many comments and it's equally hard because it's difficult to see the code through the comments.

I think the answer is in determining what information isn't already being provided by the code. Variable names tell you what information is being worked with. Operations and function names tell you how those variables are going to change. Because the code is meant to tell the computer what to do it's also good at telling the reader what it's doing. The only thing missing is why. Why are you calling this function with these arguments? Why did you implement that algorithm a certain way? Why aren't you using this feature of the language? As much as possible you want your code to tell the reader everything they need to know but comments can be added to fill in gaps. They help to explain to future people reading the code why you did certain things a certain way if it's not obvious.

The same goes for documenting your own classes and functions. The class name, methods, and fields should tell you a lot about what the class if for. Similarly a function name, parameters, and return type can tell you what it will do. Again the only thing missing is why. Why would I want to use this class instead of another? Why would I want to call this function? That information can be put in comments on the class or function. Then people thinking about using that class or function can understand the scenario it's meant for and decide if it meets their needs or not.

Comments: