DEV Community

Discussion on: My take on commenting code - Explain why, not how

Collapse
 
katafrakt profile image
Paweł Świątkowski • Edited

For me, the most important reason to write the comments is when I know that the code in question is counterintuitive. For example, a code that I wrote yesterday:

total = 0
products.each { |p| total += p.price * p.quantity }
total
Enter fullscreen mode Exit fullscreen mode

This code screams USE MAP DUDE:

products.map { |p| p.price * p.quantity }.sum
Enter fullscreen mode Exit fullscreen mode

Well, as it happens, products is not an array, but an object from an external library, that implements each but doesn't implement map (don't ask). I know that me in 4 months and any other person might not remember that and will sigh and try to refactor this code, only to fail. That's why I'd put a comment explaining why this code looks this way.

Collapse
 
nombrekeff profile image
Keff • Edited

Fantastic reason, thanks for sharing!

And a really nice point, adding comments when refactoring, renaming or creating a new method is not possible, for example for 3rd party libraries, as you mentioned! This would fall into the "comment why not how" idea, as you can't control the how in this case.