Ok, maybe hate is a strong word, but I generally try to avoid commenting my code. Why?
I want to try to make the code I write understandable and read like well written prose. Does all of my code look like that? No, but I wish it did.
If I feel a line of code needs a comment, then I feel it’s better to extract that line into a function that will describe what it’s doing rather than adding a comment. This is my preference and I will admit that. I don’t say everyone else must code this way, but it is what I prefer. So let’s look at an example.
Public Function WrapArrayOfSqlTextElementsForValuesClause(arrElements As Variant) As String
Dim retVal As String
Dim ele As Variant
For Each ele In arrElements
retVal = wrapInSingleQuotes(retVal) & ","
Next ele
If Len(retVal) > 0 Then retVal = Left(retVal, Len(retVal) - 1)
ProcessSqlElements = retVal
End Function
Let’s say I felt the need to comment the If statement following the loop with something like:
' Remove the final comma from the list
If Len(retVal) > 0 Then retVal = Left(retVal, Len(retVal) - 1)
I would rather pull this out into it’s own function to make it clear what it does rather than add the comment:
Private Function RemoveFinalComma(ByVal ElementList As String) As String
Dim retVal As String
If Len(retVal) > 0 Then retVal = Left(retVal, Len(retVal) - 1)
RemoveFinalComma = retVal
End Function
I feel that then my final line of main code is more descriptive and I am able to debug it more easily and understand what it’s doing better when I return 12 months later:
Public Function WrapArrayOfSqlTextElementsForValuesClause(arrElements As Variant) As String
Dim retVal As String
Dim ele As Variant
For Each ele In arrElements
retVal = wrapInSingleQuotes(retVal) & ","
Next ele
retVal = RemoveFinalComma(retVal)
ProcessSqlElements = retVal
End Function
The main problems I find with comments is:
- They don’t age well. If i change the code, I rarely change a comment related to it. Then it’s no longer helpful, it’s a misdirecting lie.
- Putting the descriptions in the variable and function names makes the code more readable and understandable and is a better code practice, in my opinion.
- Anything a comment can keep track of (like logging changes) is usually better tracked in a version control system with good log messages to encapsulate the overall purpose of changes.
So, I don’t want to remember to maintain my comments or have to update them when I make code changes. Again, I won’t rail against you if you use comments. I just don’t typically find them all that helpful. I’d prefer the code that is going to be compiled and executed to be telling me what it’s doing.