DEV Community

Andreas Klinger ✌️️
Andreas Klinger ✌️️

Posted on

Good comments explain WHY, not WHAT, and 3 more rules on writing good comments

Comments… I know right… What a 🔥 topic to discuss. I hope the servers can handle our excitement…

But jokes aside. If you work daily with code good comments are essential to your productivity in any mid to large sized codebase. Ugh. What a buzzkill…

So let's get to business: Comments aren't additional to a good codebase. They are the codebase.

Here a few tips to enable you to write better comments…

#1 Your comments should explain WHY not WHAT

"Comments shouldnt be needed. Good code should explain itself what it does."

If you assume this you misunderstood what comments should do.

Comments should never explain what the code does. The code itself should.
Comments should explain why it exists, and why it exists in this way

WHY vs WHAT:

  • Code should explain WHAT
  • Comments should explain WHY this code exists or WHY it has to do something in a non-obvious way.

Bad:

class Newsletter
  # removes stuff from newsletter
  def remove(stuff)
  
  end
end
Enter fullscreen mode Exit fullscreen mode

Good:

class Newsletter
  # Note(andreasklinger): In case we run into XYZ we need to remove the user to avoid
  #   problems w/ ABC and DEFG's API. Read more here: https://.....
  def remove(stuff)
  
  end
end
Enter fullscreen mode Exit fullscreen mode

#2 Leave your name

At Product Hunt we have the habit of always leaving a name next to a comment.

eg:

Note(andreasklinger): This is a comment.
Enter fullscreen mode Exit fullscreen mode

But you can use git blame for that.

People will move code around, People will edit your lines (remove trailing spaces anyone?).
Nobody will bother to find the author once code got moved around or edited often enough.

Especially in smaller teams just the name alone helps you to understand why something exists or if you should bother trying to fix/improve it.

#3 Be thorough

The "next developer taking over" is almost a myth.

Usually the "next developer" is just "quickly passing by" has her own thing she wants to get done and your code got in the way.

Imagine the next person landing in your code to have no context whatsoever and VERY limited time to change it.

While you wrote the code it was obvious to you - it will never be that obvious again - to no-one, including you.

  • Explain without the assumption that people already know how your system works
  • Explain the quirks of external systems that you have to consider
  • Explain the quirks of internal systems that you have to consider
  • Explain which parts of the system are Legacy
  • Explain when (eg legacy) code can be removed (leave a "after X is done" or a date whenever possible)
  • Explain the hacks you needed to do and why they work
  • Explain the internal interdependencies that arent explicit (eg other systems relying on structure or api)
  • Be ok w/ writing a longer paragraph whenever needed
  • Never use external documentation if you can avoid. If it's not in the same file people won't update
  • Ask to "Leave a BFN" (leave a big f*** note) - expect also your coworkers to leave notes to any code whenever needed

#4 Avoid clutter

Explicit > Implicit BUT you want to avoid explicit when explicit becomes redundant.

Write your comments.
When you wrote your comment read it again and see what you can remove or simplify.

If you can't explain it simply, you don't understand it well enough.

  • Albert Einstein

Hope that helps!

Comments aren't additional to a good codebase. They are the codebase.
While code makes a complex systems manageable for machines comments make them manageable for humans.

hth,
feel free to hit me up on twitter!

@andreasklinger

Top comments (13)

Collapse
 
codencaffeine profile image
Coding on Caffeine

Great article. I don’t fully agree with developers leaving their name, since the code and comments would go through a peer review under most processes. It’s essentially the team’s code, and the developer’s name would just be clutter once the team accepts the code and comments in a peer review.

Lots of good points in here though.

Collapse
 
andreasklinger profile image
Andreas Klinger ✌️️ • Edited

in general agree
but most knowledge work has fragments of informations that you don't represent in the artifacts you create
or differently put: need to know more -> that person will know more

git blame never really worked for this imo

Collapse
 
chris_kobrzak profile image
Chris Kobrzak

I highly recommend taking a look at Clean Code by Robert C. Martin (a.k.a. Uncle Bob).

The author argues there's no such thing as good comments as the very fact you need them often indicates the code might've been written in a confusing way. Strive at writing simple, well-structured code that adopts good naming conventions and in most cases this will be enough to steer clear of cluttering the code with comments.

Another major issue is they tend to get out of sync with the code: imagine a developer making a change a few months down the line, forgetting to update the comment above. You then look at the file in confusion as you're not sure whether it's the comment or the actual code that's correct. I've been in this kind of situations many, many times.

Collapse
 
andreasklinger profile image
Andreas Klinger ✌️️

i don't buy the "good code doesnt need comments" anymore

even the best code can't explain oddities in partner libs or complicated domain logic

and i have yet to meet a company that never changes it's product and achieves "best code" over a longer time.

code has several dimensions:

  • the file / component (what a it does)
  • the system interconnection (how stuff fits together)
  • the product usecases (how users actually use it / domain logic)
  • the changes over time (legacy / pivots etc)

good code can explain the first dimension
barely the second
hardly the 3rd
almost never the 4th

thus: "explain why not what"

Collapse
 
mrsacs profile image
Colin • Edited

I agree for the most part that you should explain the "why not what" but of the four things you list above, you might argue that

  1. What it does - agree

  2. System interconnection does not belong in the comments unless it that part of the code is orchestrating the interconnection and the code is unable to make that clear. Comments like "This will be use by x for y" may not be useful as other components using this code may change what they do leaving the comment stale.

  3. Product usecases are really not appropriate for a comment in my view unless they are used directly to build/generate the documentation (for example using a tool like Docular).

  4. Changes over time - If done wrong this can leave a lot of stale information in the source that someone skimming over might draw incorrect conclusions from. If it is felt there is a need to write this is the code in comments it suggests to me that the commit log is not being maintained well for that code. Good commit log messages leads to a good story of what changed and why. I'd argue that writing good commit messages is more important with respect to changes over time.
    As a side note, for this if using git, learn interactive rebasing... it is in my view the path to a readable commit log.

Collapse
 
rndjeff profile image
Jean-François Héon • Edited

I'm all for having the minimum amount of comments necessary.

Also, there are lots of good reasons to have comments. Sometimes, you're at the boundaries of systems. Made-up example: you have to pass an empty object instead of a null or the other way around for whatever reason the other system (that you might not control) expects. You leave a comment. It's not about making a comment "I'm returning a null", it's about "I'm returning a null because the other library is behaving badly with an empty object or whatever."

Sometimes, you think a code might be easily refactored, but you plunge in it and several dependent classes later you realize there are justified reasons why the code is written a certain way. A small comment can save hours to the next scout who wants to "leave the campground cleaner."

Or, you're choosing a particular hashing algorithm for certain useful or important properties for your use case. Please leave a comment explaining why. If not, someone else might just modify it for a more popular algorithm without realizing the unexpected impact in performance and of security.

Especially in shops or projects with high turn-over or which lives for decades, history and business logic gets lost.

Collapse
 
karfau profile image
Christian Bewernitz

WE recently discovered that we need to document the assumptions hidden behind (S)CSS classes.
When using lots of loosely coupled (React) components, things get unmaintainable pretty soon, if this information is hidden in tickets and pull request comments.

Collapse
 
codemouse92 profile image
Jason C. McDonald

Great to see someone else promoting this style of commenting! My company actually has a standard based on this idea: Commenting Showing Intent.

Collapse
 
nucleareaglefox profile image
NuclearEagleFox

I fully agree based on the context I assume you're talking about (professional), and I think I know where the impulse toward what-type comments stems from: school.

What-type comments make sense in a learning situation where the teacher or professor has to quickly traverse many students' code and understand their implementation. Also, early in their skill development, student coding styles and naming conventions vary wildly, comments allow the instructor to classify different sections of student code easily. I can imagine an instructor reading a comment and thinking, "Oh this is the function they use to re-order their heap", or something similar.

This leads to think that different comments/documentation are needed in different contexts. In a professional environment, with standardized documentation and naming conventions, "what" is usually covered elsewhere and unnecessary. But in educational contexts, where the user is the instructor, a different strategy is needed.

I think the problem you describe stems from the failure of students and sometimes managers and supervisors to fully context switch and adopt a the style you're writing about.

Collapse
 
faridzif profile image
Faridzi

Love this really. Meanwhile the culture of my company still struggling with the basic good and simply code, others even manage to discuss this sort of stuff. Cool community once again :)

Collapse
 
idesi profile image
Watandeep Sekhon

Great article. At my company, comments explaining "what" are usually the first to get shot down in code reviews.

Collapse
 
waylonwalker profile image
Waylon Walker

I like the addition of names in the comments

Collapse
 
johannesvollmer profile image
Johannes Vollmer

Be ok w/ writing a longer paragraph whenever needed

:D