The original link: https://testing.googleblog.com/2017/07/code-health-to-comment-or-not-to-comment.html

Front-end-basics is a github notebook that is constantly updated.


When reading code, an appropriate comment is often useful. However, can not be arbitrary annotation. And sometimes the code needs comments, which usually means the code should be refactored.

Comment when your code is not self-explanatory. If you feel the need to add a comment to explain what the code is doing, try one of the following methods:

Introducing a variable

// Subtract the discount from the priceFinalPrice = (numItems * itemPrice) -min (5, numItems) * itemPrice * 0.1;
price = numItems * itemPrice;
discount =
    min(5, numItems) * itemPrice * 0.1;
finalPrice = price - discount;

Pull out a method

// Filter sensitive words
for (String word : words) { ... }
filterOffensiveWords(words);

Use a more descriptive identifier name

int width = ... ;// The width is in pixels
int widthInPixels = ... ;

Add a check to your hypothetical code

// height > 0 is safe
return width / height;
checkArgument(height > 0);
return width / height;


Here are some pertinent and useful notes:

Make your intentions clear: Explain why the code is written the way it is (not what it does)

// Because of the high performance, so only once

Prevent well-meaning maintainers from later “fixing” your code incorrectly

// Since Foo is not thread-safe, create a new instance of Foo

Description: Problems found during code review or problems encountered by people looking at the code

// Note: Orders are important because...

Explain the reasons for what may seem like bad software engineering practices

@SuppressWarnings("unchecked") // This list is safe because...


In other words, avoid comments that simply repeat what the code does. Such comments are useless and annoying.

// Get all users
userService.getAllUsers();
// Check if name is null
if (name.isEmpty()) { ... }