Write comments only when they answer the “Why?”

This is the one and only question that I ask myself when I see comments or when I feel that I need to write some:

Do these comments provide the reason why this code was written?

If not then 99.9% we don’t need them.

“Remove right margin”

I recently came across a block of code that looked like this:

private fun foo(ui: Ui, system: System) {
val isGridLayout: Boolean = ui.itemsAreInGrid()
// Remove right margin when the theme is light and the layout is a list
if (!isGridLayout && !system.isDarkThemeEnabled()) {
val uiContainer = ui.container
uiContainer.rightMargin = 0
}
}

In this example the comment simply describes what the code does. I am pretty sure that everyone can figure that out but only the code’s author knows why we need to remove the margin under those circumstances. I am also sure that in six months (in my case in six days) even the author won’t remember the reason behind this code.

Extract if’s logic

To be fair I do understand the author’s urge to write this comment. Those unavoidable negations, because of the system’s/ui’s APIs, look like they need to be clarified.

Fortunately there is a better way to do that: we extract if’s logic to its own method and name it accordingly:

private fun foo(ui: Ui, system: System) {
// Remove right margin when the theme is light and the layout is a list
if (inLightModeWithItemsInList(ui, system)) {
val uiContainer = ui.container
uiContainer.rightMargin = 0
}
}
private fun inLightModeWithItemsInList(ui: Ui, system: System): Boolean {
return !ui.itemsAreInGrid() && !system.isDarkThemeEnabled()
}

Extract if’s body

We can go a step further and extract if’s body to its own method too, having the code replacing the comment completely:

private fun foo(ui: Ui, system: System) {
if (inLightModeWithItemsInList(ui, system)) {
removeRightMargin(ui)
}
}
private fun removeRightMargin(ui: Ui) {
val uiContainer = ui.container
uiContainer.rightMargin = 0
}
private fun inLightModeWithItemsInList(ui: Ui, system: System): Boolean {
return !ui.itemsAreInGrid() && !system.isDarkThemeEnabled()
}

Answer the “Why?”

So now what is missing is the reason behind the margin’s removal. A comment that answers the why and completes the reader’s understanding about the code she/he reads.

private fun foo(ui: Ui, system: System) {
if (inLightModeWithItemsInList(ui, system)) {
// blah blah …
removeRightMargin(ui)
}
}

“I can see what is happening and I know why too!”

Leave a comment