DEV Community

Discussion on: 10 practices for writing readable code

Collapse
 
alexm77 profile image
Alex Mateescu

Except for removing comments, the article reflects my thoughts pretty well, too. Code full of comments is arguably just as bad as code with no comments at all. But trickier parts of code need to be commented. No matter how obvious the implementation might be, it's important to document your intention. You never know when you'll get something wrong and if your intention is not written down, it will be impossible for the next person to determine when something goes wrong if it's because of the requirements or the implementation.

Also, while I have just found out about the rule of three, it turns out I have been advocating in its favour for years.

Collapse
 
syncsynchalt profile image
Michael Driscoll

I've found a better way to pitch "remove comments": When you see a one-liner comment, there are two opportunities for its removal:

  1. if the comment is above the function or method definition, maybe the function can be renamed in a way that removes the need for the comment
  2. if the comment is within the function or method, maybe the code block that it's commenting can be extracted into its own function/method with a name that will reflect what the comment is trying to say

In this way our comments become reflected in the code itself, making the code more readable/understandable, more resistant to comment rot, and more meaningful to tools like IDEs.

One more statement: Not every comment can/should be removed, this is not absolutist advice.

Collapse
 
gonedark profile image
Jason McCreary

I would challenge, "why is the code tricky?"

Collapse
 
alexm77 profile image
Alex Mateescu

It sometimes just is.

You can have something as simple as:

return x / 3;

and in the absence of a comment you can't tell whether that was supposed to divide by 3 or by anything else.
Of course, in this particular case you can use a suitable method name and not use a magic number. But I think you get my drift, sometimes the business logic itself is not self-explaining (i.e. explaining why a null check is present where it's not obvious why and whatnot).

Thread Thread
 
ashleyjsheridan profile image
Ashley Sheridan

A good rule of thumb is to comment about the 'why' and not the 'how' or 'what'. This means that the comments that are left are the ones that aren't obvious from the code.

Of course, as with anything there are exceptions, such as dealing with magic values from external sources or one that I've had to do recently: comment what a series of regular expressions were doing!

Thread Thread
 
alexm77 profile image
Alex Mateescu • Edited

Another favourite of mine is when the production code has checks for something that's injected only for tests. To add insult to injury, those tests are usually called... wait for it... unit tests!

Otherwise, yes, that looks like a sensible rule.