DEV Community

jessicabetts
jessicabetts

Posted on • Edited on

No Comment(s)?

no comment

I’m just going to get this out of the way… commenting your code is tedious, I know! Many of us developers don’t enjoy it and often times neglect it completely. Short term it sucks. It takes up time and its boring. BUT IT IS SUPER IMPORTANT. I promise commenting is made to help you!!! The purpose of a comment is to make your life easier. I made this blog because I don’t feel that the importance of commenting is stressed enough in education.

Its all about you!

all about me

READABILITY. READABILITY. READABILITY.

Let’s say you have created a project. 6 months down the road you decide to go back to the code and rewrite it in a new language you have just learned. You are perusing your code, and come across a function you don't understand or do not remember writing. Imagine how much more understandable the code would be if there were some comments explaining what is happening.

  def self.valuable?(word) #checks to see if the word should be kept
    valuable = false
    if /[[:upper:]]/.match(word[0]) #if variable
      valuable = true
    elsif word == '"quote_placeholder"' #if string/quote
      valuable = true
    elsif word == '#comment_placeholder' #if comment
      valuable = true
    elsif word == '(param_placeholder' #if params
      valuable = true
    elsif word == 'class_word_placeholder' #if class
      valuable = true
    elsif word.to_i.to_s == word #if num
      valuable = true
    elsif OPERATOR_KEYWORDS.include? word #if operator
      valuable = true
    end
    valuable
  end

It’s not all about you!

comes across as selfish

This concept becomes more important when you are working in a team of developers or when taking over legacy code. Most people would agree, It is much harder to debug someone else’s code than your own. However, this is what developers do. Sometimes you write new solutions to new problems but often times you will be fixing someone else old code. Because it is easier to understand someone else's code if it has comments, you should do the same.

Abstraction

Commenting will allow people who are unfamiliar with your code to understand more quickly. Rather than reading line by line, one can simply read about its functionality in the comment. This also allows non-programmers to be able to understand your code more clearly. The amount of time it will take to understand the functionality of a method will be greatly increased if the previous developer did not comment their code and do it WELL.

When should you comment

It is my opinion that we have a duty to be commenting all code that:

  • others will touch/see
  • lengthy
  • will be used/looked at in the future
  • is not super intuitive
  • is not adhering to single responsibility principles
  • is not adhering to descriptive naming conventions

Basically always.

Examples:

Function name
Input: Type
Output: Type
Purpose: A brief description of what is accomplished.

/*
findStart
input: an array of brewery objects
output: a single brewery object
purpose: finds which brewery you should start with on your brewery crawl
 by:
 - finding the center point of all breweries
 - finding which brewery is farthest from that center point
*/

static findStart(breweries) {
  let coords = Map.getCoords(breweries);
  let center = Map.findCenterPoint(coords)

  let greatest_diff = 0
  let start = null
  breweries.forEach(brewery => {
    let diffLat = Math.abs(center.lat - parseFloat(brewery.latitude))
    let diffLng = Math.abs(center.lng - parseFloat(brewery.longitude))
    let totalDiff = (diffLat * diffLat) + (diffLng * diffLng)
    if (totalDiff > greatest_diff) {
      greatest_diff = totalDiff
      start = brewery
    }
  })
  return start
}

Do yourself a favor. Do your fellow coders a favor. Comment your code.

Top comments (7)

Collapse
 
levivm profile image
Levi Velázquez • Edited

I think you mean "documentation", because leaving comments is different from documenting your code.

Just my opinion, people should spend more time trying to use proper variables name, code refactoring and thinking about good function definitions than leaving comments. Why? Because if you need to leave comments to allow another teammate to understand your code, it means your code itself is not quite clear.

Example:

def buy(u, t)
     # function to buy a ticket t from a user

Better

def user_buy_concert_ticket(user, ticket):
.........

The second one doesn't need any explanation. It would require a bit more of "abstraction" and re-thinking but it's worths it.

So, leaving a lot of # with comments spread over the whole function could distract the user from the function itself, as well, if you change your logic, you will need to change the comments too. It means "double work".

I recommend: try to create your function in a way it does just One Thing rather than having a lot of processes within one scope and leaving comments.

Again: this is just my opinion, everyone could have their methods, I'm just trying to add a different perspective to the thread.

It is very nice that you open this thread because it would help a lot of developers. This is a common struggle.

Collapse
 
appeltel profile image
Eric Appelt

So even with the improved version I'm a bit confused:

def user_buy_concert_ticket(user, ticket):
.........

Am I buying a ticket for a user or am I buying a ticket from a user? We've lost the relationships between the action, direct object, and indirect object. What are the side effects? What account is being used to provide funds, some global?

What does the function return? Maybe True/False depending on if the transaction succeeded? Or maybe it returns some type of receipt and throws some exception if it fails? I don't know.

This is just as scary when I modify the function as when I use it. I don't know what the implicit API contract is and I don't know if my modifications might break existing calling functions in strange ways. Its possible that I do something that misses all paths for a reasonably robust set of unit tests in the package.

While I agree that some effort should be but into self-explanatory code, its simply too tall an order in principle, and impossibly difficult in practice to explicitly state the full behavior of a function in its name and call signature - even with static typing or type hinting. I'll also admit that for private or locally scoped informal helper functions that won't be called outside the module or functional unit its ok to lack a specification.

So for the above function one could write a docstring or specially formatted comment as follows:

def user_buy_concert_ticket(user, ticket):
    """
    Buy a ticket from a user, and return True if the transaction succeeded, False otherwise.

    Funds to purchase the ticket are taken from the configured global account general.
    """

Now I have an API contract that I can test against, depend on when I call it, and understand my limitations when I make changes. Even better, with some minimal tooling I can use properly formatted comment or docstring to autobuild the API documentation. So when I change the function, I can change the documentation.

There are even tools and approaches where you can embed tests into your docstring so the comments so that the API contract is stated, documented, and checked all in the same place right alongside the code.

I also think it makes the what and how of the code easier to read after one has placed the contract summary into their head. Furthermore, consumers of the function don't need to read the code at all, everything they need to know is in the docstring.

Collapse
 
levivm profile image
Levi Velázquez

Hi,

I just gave a simple example, of course, maybe I should add more examples and not only at the beginning of the function, in fact I didn’t provide any context, it just was trying to explain why we should put more emphasis on naming and proper variable name usage, I didn’t specified if that was an API, etc.

I’m totally agree what you did but that is the difference between leaving comments and create documentation, you are using embed tools for creating an a contract for an API, documentation is much higher level, I stated the difference. I’m agree with creating docstrings( in python for example) but it is a difference thing from leaving comments. If you are in the middle of the function, you can’t use docstring. If you need to leave a comment to explain what are you doing: 1. Likely your function is doing more than One Thing and I don’t recommend that 2. Your code isn’t clear 3. And if your change your logic you need to mantain code and comment as well.

Collapse
 
jessicabetts profile image
jessicabetts

I've never used docstrings, sounds like something I should check out! With the added testing it sounds even more useful.

Collapse
 
jessicabetts profile image
jessicabetts • Edited

I totally agree that code design is more important than commenting! Proper design makes things super readable, like in your example above. I believe that you are right that in most circumstances having proper design can eliminate the need for commenting. However, I did mean commenting, not documenting and I still feel that commenting can be super useful if something isn't intuitive!

Thanks for your feedback, valid points!

Collapse
 
kvsm profile image
Kevin Smith 🏴󠁧󠁢󠁳󠁣󠁴󠁿

I think your conclusion (that commenting should be used where code isn't intuitive) is bang on the money - I just think that the cases where it's acceptable for code to be unintuitive are very rare.

At my workplace, for example, comments aren't generally permitted at all. The only case I can think of which would pass code review would be when you have no choice but to do something non-obvious due to a quirk of some external library or system. In all other cases, code with comments would be rejected because:

  • Code which needs comments to be intuitive should be refactored so it doesn't need comments to be intuitive; and
  • Comments can't be tested, so it's hard to know if the message left in one is accurate either at the time it's written or (more importantly) at any point afterwards.

This might seem super rigid, and does feel that way on occasion, but I do believe (and observe in practice with our junior devs) that getting into the mindset of avoiding writing comments does improve code quality over time.

Thread Thread
 
jessicabetts profile image
jessicabetts

Valid!

I think everyone should strive for code that doesn't need explanation! It is interesting how different areas within the programming community feel differently about this. In college, every assignment HAD to have comments. Maybe that was more about making sure we understood what was happening? At coding bootcamp we haven't touched on commenting at all!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.