Please stop code comments

"Clean code should be written like prose" - Robert C. Martin

A common problem is that there are a lot of bad code comments. This is messy source code of the most visible signs.

Each programmer goal should be to write clean and expressive code to prevent code comments. Each of the variables, the objective function and the like should be implied in its name and structure.

When other people read your code, they should not read the comments to see what your code is doing. Named good classes and functions should guide the reader through your code, like a well-written fiction. When the reader sees a new category or function, they should not be confused difficult to understand what they see in it.

Remember, very few developers working time is spent on writing code spend time reading the code and understand the code much more .

Notes to cover up their own failure

I often see comments describing the code above the variable or function name to perform (or operations that should be performed) content. These comments gave me the feeling is that the former eyebrow this code there are ways to imagine a name expressive, or their function is not just one thing.

Named in the code is very important. You should spend a lot of energy every piece of code named accurately and precisely, so that other developers can understand your code.

// 按状态查找员工
List<Employee> find(Status status) {
  ...
}
复制代码

In this example, the name of the find is not described, the authors of this function need to leave descriptive comment function describing function. When we see the find function called from another module, its role is a mystery. It found? What does that mean? It returned to what it found it? How to find what it found? Like Uncle Bob in his book "Clean Code" in said, if you need to write a comment, you can not express their true intentions by code.

We do not want to check the function of each of the above comments, in order to understand its role.

List<Employee> getEmployeesByStatus(Status status) {
  ...
}
复制代码

Now obviously can see that the specific role of this function, which makes comment unnecessary. It makes me think of a way to the next comment failed.

Redundancy comments

These confusing your code, completely unnecessary. Add a number of redundant comments will guide readers to the formation of these comments are "boring" mentality, skipping every comment, so when there are important notes, will not be read.

//此函数发送电子邮件
void sendEmail() {
  ...
}

//此函数发送电子邮件
public class Employee {
  ...
}

/ **
* @param title CD的标题
* @param作者CD的作者
* @param track CD上的曲目数
 * /
public void addCd(String title, String author, int tracks) {
  ...
}
复制代码

In most cases is compulsory redundancy. Many companies in each functional category and require this. If your boss asked to do so, emm you can try to ask them not to.

Wrong level of abstraction

If you have a long record function or which part of the code needs to do something, then you may be in violation of these rules:

  1. Function should do one thing.
  2. Function should be minimal.

This is an example

//此函数计算价格,与销售额进行比较
//促销,检查价格是否有效,然后
//向用户发送促销电子邮件
public  void doSomeThings(){

  //计算价格
  ...
    ...
    ...
  
  //将计算出的价格与促销活动进
  ...
    ...
    ...
  
  //检查计算的价格是否有效
  ...
    ...
    ...
  
  //向用户发送促销信息
  ...
    ...
    ...
}
复制代码

When you successfully encapsulating each portion into a single logic function, the code does not need to be annotated image will exhibit its effects as described.

Reconstructed as follows:

public  void sendPromotionEmailToUsers(){
  calculatePrices();
  compareCalculatedPricesWithSalesPromotions();
  checkIfCalculatedPricesAreValid();
  sendPromotionEmail();
}
复制代码

Note instead of each portion of code, each logic block should be well encapsulated in its own function.

First, it improves readability . Each code block need not read line by line. We can simply read the auxiliary function name and understand its role. If we want to learn more details within each function, you will be able to see the implementation.

Second, it increases the testability . In the above example, we can function separately for each unit test. If the package does not separate functions, it is difficult to test a larger function sendPromotionEmailToUsers () of each part. Function to perform multiple functions difficult to test.

Finally, it increases the reconfiguration . By each portion of the package to their logical function, future changes easier to maintain, and the function of the individual functions are isolated to only change the behavior of the function. When we use the local variables of the function persist throughout the length of the function, since the function of tightly coupled, it is difficult in the case does not result in the reconstruction function changes elsewhere.

Commented code

Comment out the code should be seen as roadkill. Do not look at it, it is not news, do not ask where it comes from, just get rid of it. The longer it remains, the longer the time remaining code smell ......

/ *
public void oldFunction(){
  noOneRemembersWhyIAmHere();
  tryToUnCommentMe();
  iWillProbablyCauseABuildFailure();
  HAHAHA();
}
* /
复制代码

Although you do not delete delete delete others are afraid. If you need it later, you can always check the version control system, because you must use the VCS, right? (If not, when I did)

TODO comment

Do not write TODO comment, and not just ...... do it? Most of the time these notes will be forgotten, and later may become irrelevant or wrong. When another programmer to see the TODO comments later, how do they know whether the need?

But occasionally TODO comment is good if you are waiting for another merger teammates (usually not for long). You can do until you can fix and submit it.

"When you feel the need to write a review, we must first try to refactor the code so that any comments have become superfluous." - Martin Fowler

Notes Lies

When Jimmy wrote in his new function marked above comments, he thought he was helping in any future developer to see his code. In fact, what he was really doing was setting a trap. His comments may be big lie (no pun intent) dormant for months or years without being touched, just waiting to become a nasty trap. Then one day, in one of hundreds of reconstruction and demand changes in his comments from a number of remote modules fail, but still in the wrong boot disk access countless Xia.

When you change one line of code, how do you know the code you can not make changes to the rest of the comment is not valid? There is no way to know. Comments must be destroyed

public class User {
  ...
  //它包含用户的名字和姓氏
  String name;
  ...
}
复制代码

Then, the demand for change, they want to split the name into firstName and lastName.

public class User {
  ...
  
  // 它包含用户的名字和姓氏
  String firstName;
  String lastName;
    
  ...
}
复制代码

Comment now wrong. You can update the comments to reflect the changes, but if you really want to manually maintain all comments after each change? You're a developer, rather than documents.

But the comments could easily be noticed and there is no need to change the problem. But it's hard to guarantee that elsewhere in the program, will also comment this parameter name is the user's first name and last name. Place a small piece of code changes, you may make a lot of code comments are invalid.

Let's look at another example:

//根据状态处理员工
void processEmployees(){
  ...
  List < Employee > employees = findEmployees(statusList);
  ...
}

//这会按状态列表查找Employees
List < Employee > findEmployees(List < String > statusList){
  ...
}
复制代码

Then someone was asked to change the function findEmployees, to list by name rather than find a list of state employees.

//根据状态处理员工
void processEmployees(){
  ...
  List < Employee > employees = findEmployees(statusList);
  ...
}

//这会按状态列表查找Employees
List < Employee > findEmployees(List < String > nameList){
  ...
}
复制代码

First, the above comments findEmployees has failed, and therefore needs to be changed. No problem, right? Wrong .

processEmployees above comments also fail, and therefore need to be changed. How many other comments this was changed to invalid small remodeling? This change creates a number of comments in the source code lies?

alternative plan:

void processEmployees(){
  ...
  List < Employee > employees = findEmployeesByName(nameList);
  ...
}

List < Employee > findEmployeesByName(List < Name > nameList){
  ...
}
复制代码

If you are accurate and accurately name your function, you do not need a comment, and you will not be spreading lies in the code.

"Code never lie, comments are." - Ron Jeffries

When do you need it Notes

I know a lot of developers are die-hard supporters of the code comments, for them, I must admit that sometimes comments are possible. But each paragraph you write should have a good reason

Complex expressions

If you have a complex SQL statements or regular expressions, please continue to write a comment. Express statements like cleanly in the code can be difficult. In these expressions to add comments above can help other developers to better understand your code.

// 格式匹配kk:mm:ss EEE,MMM dd,yyy
Pattern timePattern = Pattern.compile("\\d*:\\d*:\\d* \\w*, \\w*, \\d*, \\d*");
复制代码

Notes Warning

If you need to warn other developers that may occur this code bug, you can leave a comment in the vicinity of this code. These comments may serve as a code of conduct mysterious aura, and add value to your code.

Clarify the intent

If you really named waste, it would have to bear your failures and write comments. You are responsible for writing the code, so do not ever put a poorly-written code for stay.

If you have to write a comment, make sure it is local. Comment away from its non-local references destined to fail and become a lie. Reference a function or variable comments should be located directly above it. Caution note may be above or beside the code it references. If your IDE supports comments highlighted, please make your comments stand out from the rest of the warning code.

At last

I have created feelings of code comments. I despise them, but I know that sometimes they are needed.

So, please stop to write so many comments.

This paper is to see a large foreign god Brian Noland discussion on Twitter, So deep that it be post-translational modifications made to share. I hope that their code could be like as elegant prose.

How not to write your code comments
, "I am sorry, my code is not written comment" (escape

Guess you like

Origin juejin.im/post/5cf60bc8f265da1baa1e609e