Should you comment your code?

Something that I hear often is "self-documenting code", and that code should be easy to understand without comments.

If you need to write a comment explaining what something does, move the code into a new class or function and have its name describe what it does.

I agree with this, but I still think there is a place for comments within the code as long as they add value.

What comments shouldn't be

Comments shouldn't just repeat what the code says.

If the comment says "Returns false", and I can read that from the code, the comment isn't adding any value.

I use types a lot in PHP and TypeScript, and if docblocks are just repeating the native types, I'd rather not include them and keep the code minimal.

Comments like "Constructor" and "This shouldn't happen" add no context.

What comments should be

Comments need to add value by adding extra information or explaining why the code does what it does.

I will add comments like "This class decorates ... so that ..." and "This returns ... if ...". These comments add value and make the code easier to read and understand. The downside is that you then need to maintain the comments, make sure they remain correct, and if the functionality changes the comment is also changed.

If a static analysis tool requires me to provide more information in a docblock that describes some parameters or a return type, I'll do that. It makes the code quality better, reduces bugs, and makes the Developer experience better. As I'm improving the native types by providing more information, I'm not just repeating them so this is OK with me.

Comments should make the code easier to read, understand, and work with for yourself and other team members.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.