From my experience, if your code is well written, you don't have to write what it does. But always, no matter what, you shall write why it does it and why not the other way.
Consider the following example snippet. This comment is useless:
// Adding fullname property to customers
customers.forEach(_ => _.fullname = `${_.name} ${_.surname}`);
Because you can obviously read that from the code. However:
// Enriching customers data by caching full name as a property.
// This is later used in both display and some processing to
// reduce boilerplate code
customers.forEach(_ => _.fullname = `${_.name} ${_.surname}`);
From this comment, not only you know why it does it, but also you get a general idea where you would see changes if you decide to remove or modify this code. This is a priceless information if you are working in a large development team.
I found Laravel to be an excellent example of this. For instance, check out this method from SQL Query\Builder:
/**
* Add a join clause to the query.
*
* @param string $table
* @param \Closure|string $first
* @param string|null $operator
* @param string|null $second
* @param string $type
* @param bool $where
* @return $this
*/
public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
{
$join = $this->newJoinClause($this, $type, $table);
// If the first "column" of the join is really a Closure instance the developer
// is trying to build a join with a complex "on" clause containing more than
// one condition, so we'll add the join and call a Closure with the query.
if ($first instanceof Closure) {
call_user_func($first, $join);
$this->joins[] = $join;
$this->addBinding($join->getBindings(), 'join');
}
// If the column is simply a string, we can assume the join simply has a basic
// "on" clause with a single condition. So we will just build the join with
// this simple join clauses attached to it. There is not a join callback.
else {
$method = $where ? 'where' : 'on';
$this->joins[] = $join->$method($first, $operator, $second);
$this->addBinding($join->getBindings(), 'join');
}
return $this;
}
You don't even have to know the bigger picture to understand what and why the method and conditions work the way they do. In my opinion, this is what a truly good comments should look like.