DEV Community

Discussion on: Commenting: where?

Collapse
 
dvddpl profile image
Davide de Paolis • Edited

the WHY is mostly some business logic rule or requirement, or something that by thinking about the feature/functionality is cumbersome or counterintuitive. ( or maybe you want to point out some very hidden internals of a native or 3rd party method ).

const add = (a, b) => a + b
Enter fullscreen mode Exit fullscreen mode

here a comment is absolutely useless, what value would a comment like receives 2 numbers as parameters and returns one number which is the sum of the 2 add?

if on the other hand you have a method that sums number but should never return an odd number and therefore appends 1 to make the result even ( dont ask me why you would have such a method, just made that up), a comment might make sense indeed.

const noOddsAdd = (a,b) => {
  let sum = a+b
// our legacy system can't accept odd numbers 
// therefore whenever we do a sum operation we need to return an even number 
// and add 1 to any odd result;
  return sum%2 !=0 ? ++sum : sum
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
dvddpl profile image
Davide de Paolis

another reason why comments should be minimal, even to explain the WHY above is that we should have Unit Tests! Unit Tests are uptodate documentation of the edge cases and weird behaviours of a method.

test("when sum would be odd, method returns an even number anyway", ()=>{
const result = noOddsAdd(4,5);
expect(result).toBe(10)
))
Enter fullscreen mode Exit fullscreen mode