Read the summary of code neatness

Keywords: Java C#

  I read clean code in English for a long time. At that time, the blogger was a green rookie and was creating chaotic code for the team. Over the years of work, I have been repeatedly trapped by other people's code. Recalling the code I left in those years, I must have harmed my later colleagues. When reading JDK source code or other excellent open source projects, I marvel at the excellent construction of the author's code. They all have common characteristics: accurate variable names, appropriate design patterns, detailed but not repeated comments, and so on. Now reread this book, summarize the content and add some of your own opinions to share with you.

  work communication is not only email or face-to-face language communication, but also code. Realizing requirements with code is only the first step of the long march. You must let the code express your design ideas. Imagine that another colleague takes over the function you are responsible for. If your code structure is clear and the comments are reasonable, he doesn't have to frequently ask code doubts and interrupt your work. When writing code, you should take into account the reading feelings of others, reduce reading disabilities, and create code for the whole team, not yourself.

  this is the proverb of the American Boy Scout rules. The American Boy Scout is equivalent to a semi military youth summer camp. After the summer camp, the children leave the camp to clean and keep clean, so that the camp is cleaner than before. In the process of software development, it can be understood as not breaking the rules and not introducing chaos. If the team has formulated code specifications, such as the class name must have subsystem prefix, such as BiOrderService(Bi refers to bi business department), continue to follow; For another example, the team has provided public libraries such as MD5 encryption, so do not introduce new MD5 libraries again. After many novice programmers take over the job, they see the specifications they don't like, start a new stove, need some tools, and don't ask the old driver whether there is a public library. They directly introduce their familiar libraries, causing compatibility or other problems.

  proper naming is a top priority, just as it is important to give a newborn a good name. Inappropriate naming usually means that words don't express the meaning, mislead the audience, excessive abbreviations, etc. because English is not our mother tongue, it seems really difficult to find a suitable word naming. My suggestion is to clarify the business first, organize the meeting to set the words in common business fields, and prohibit the team members from inventing their own words. For example, if canteen is used in the code to represent the canteen, don't invent DinnerHall, which is wordy and misleading to colleagues.

Take a counter example:

// cell-phone number
String phone = "13421800409";
// Get address
private String getDiZhi();
//Change Password
private void modifyPassword(String password1 ,String password2)

Take a look at the positive example:

// Mobile number mobileNo is more accurate than phone
String mobileNo= "13421800409";

// Avoid mixing English Pinyin
private String getAddress();

// The naming of parameters should distinguish meaning
private void modifyPassword(String oldPassowrd,String newPassword)

  there is no final conclusion on how short the method is suitable, but a method of 500 lines definitely makes readers feel like killing people. Too long method, so that readers do not know where to start, look at the front and forget the back. Split complex methods into short methods with relatively simple logic.

Take a counter example:

//  Get personal information
private UserDTO getUserDTO(Integer userId)
{
    //Get basic information 
    ... Ten lines are written here

    //Get the latest order information
    ... 30 lines are written here

   // Get wallet balance, number of coupons available, etc
    ... 30 lines are written here

   return userDTO;
}

Take a look at the positive example:

//  Get personal information
private UserDTO getUserDTO(Integer userId)
{
    //Get basic information 
    UserDTO userDTO= getUserBasicInfo(userId);

    //Get the latest order information
    userDTO.setUserLastOrder(getUserLastOrder(userId));

    // Get wallets, number of coupons available, etc
    userDTO.setUserAccount(getUserAccount(userId));  
    return userDTO;
}

private UserDTO getUserBasicInfo(Integer userId);
private UserLastOrder getUserLastOrder(Integer userId);
private UserAccount getUserAccount(Integer userId);

  why reduce nesting? Doesn't nesting look fashionable? I once saw a piece of code of a colleague nested up to 9 layers, and he was dizzy when he went to maintain it himself. The result of over nesting of code is that only the original author can understand it, and the disk receiver looks at a loss.

Take a counter example:

// Modify the user password. This example has only three layers of nesting, which is very gentle
public boolean modifyPassword(Integer userId, String oldPassword, String newPassword) {
      if (userId != null && StringUtils.isNotBlank(newPassword) && SpringUtils.isNotBlank(oldPassword)) {
	User user = getUserById(userId);
	if (user != null) {
	     if (user.getPassword().equals(oldPassword) {
	          return updatePassword(userId, newPassword)
	     }
	 }
      }
}

Take a look at the positive example:

// Modify user password 
Public Boolean modifyPassword(Integer userId, String oldPassword, String newPassword) {
     if (userId == null || StringUtils.isBlank(newPassword) || StringUtils.isBlank(oldPassword)) {
            return false;
     }
     User user = getUserById(userId);
     if(user == null) {
           return false;
      }
     if(!user.getPassword().equals(oldPassword) {
           return false;	
     }
     return updatePassword(userId, newPassword);
}

The positive example uses guard statements to reduce nesting, but not all scenarios are suitable for such rewriting. If it is not suitable, the logic with high relevance can be extracted into an independent method to reduce nesting.

  have you ever seen a super long method taken care of by a try/catch from beginning to end? In the projects experienced by bloggers, this irresponsible writing can be found everywhere. Not every line of code will throw an error, as long as the business that throws an error is placed in an independent method.

Take a counter example:

//  Get personal information
private UserDTO getUserDTO(Integer userId)
{
   try { 
       //Get basic information 
       ... Ten lines are written here
       //Get the latest order information
       ...20 lines are written here
       // Get wallets, number of coupons available, etc
       ...20 lines are written here
    }catch (Exception e) {
        logger.error(e);
        return null;
    }
}
   return userDTO;
}

Take a look at the positive example:

//  Get personal information
private UserDTO getUserDTO(Integer userId)
{
    //Get basic information 
    UserDTO userDTO= getUserBasicInfo(userId);

    //Get the latest order information
    userDTO.setUserLastOrder(getUserLastOrder(userId));

    // Get wallets, number of coupons available, etc
    userDTO.setUserAccount(getUserAccount(userId));  
    return userDTO;
}
private  UserDTO getUserBasicInfo(Integer userId);
private  UserLastOrder getUserLastOrder(Integer userId);
private  UserAccount getUserAccount(Integer userId){
      try{
          // TODO
      } catch ( Exception e) 
       { //TODO }
}

  if there are more than 3 method parameters, it is recommended to wrap them in the class. Otherwise, when adding more parameters, the caller will make syntax errors due to strong semantic coupling. The paging query interface in the background management often has many query parameters, which may be added. Encapsulation is the best.

Take a counter example:

// 6 parameters of order query by page
public Page<Order> queryOrderByPage(Integer current,Integer size,String productName,Integer userId,Date startTime,Date endTime,Bigdecimal minAmount ,Bigdecimal maxAmount) {

}

Take a look at the positive example:

@Getter
@Setter
public class OrderQueryDTO extends PageDTO {
 private String productName;
 private Integer userId;
 private Date startTime;
 private Date endTime;
 private Bigdecimal minAmount ;
 private Bigdecimal maxAmount;
}
// 6 parameters of order query by page
Public Page<Order> queryOrderByPage(OrderQueryDTO orderQueryDTO) {

}

Lombok component automatically generates constructor, getter/setter, equals, hashcode and toString methods for attributes during compilation by annotation
Examples are as follows:
@Setter annotation is on a class or field. The annotation generates setter methods for all fields when it is on a class. When the annotation is on a field, it only generates setter methods for that field.
@The getter method is the same as above, except that the getter method is generated.
@ToString annotation, add toString method in class.
@EqualsAndHashCode is annotated in the class to generate hashCode and equals methods.
@NoArgsConstructor annotates classes to generate parameterless construction methods.
@RequiredArgsConstructor annotates the class to generate construction methods for fields in the class that need special processing, such as final and fields annotated with @ NonNull.
@AllArgsConstructor annotates the class and generates a constructor that contains all the fields in the class.
@The Data annotation generates setter/getter, equals, canEqual, hashCode and toString methods in the class. If it is a final attribute, the setter method will not be generated for this attribute.

Conventional writing:

Public class Order {
     private Integer userId;
     
     public Integer getUserId() {
          return userId;
    } 

    public void setUserId(Integer userId) {
          return this.userId = userId; 
 }
}

Using Lombok:

@Getter
@Setter
Public class Order {
     private Integer userId;
}

  Apache Commons series components provide us with tools and methods on string, collection, IO operation, etc. These components are a big treasure house and provide a lot of wheels.

assemblyintroduce
beanUtilsJavaBean s perform various operations, cloning objects, properties, and so on
codecTool packages for handling common coding methods, such as DES, SHA1, MD5, Base64, etc
collectionsjava collection framework operation
configurationConfiguration management class library for java applications
ioEncapsulation of io tools
langTool class packages for Java basic object methods, such as StringUtils, ArrayUtils, and so on
loggingProvided log interface
netIt provides a data verification framework for client and server

Take an example:

Example 1: Determine whether the collection is empty:
CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false

Example 2: Judge whether the collection is not empty:
CollectionUtils.isNotEmpty(null): false
CollectionUtils.isNotEmpty(new ArrayList()): false
CollectionUtils.isNotEmpty({a,b}): true

Example 3: operations between two sets: 
aggregate a: {1,2,3,3,4,5}
aggregate b: {3,4,4,5,6,7}
CollectionUtils.union(a, b)(Union): {1,2,3,3,4,4,5,6,7}
CollectionUtils.intersection(a, b)(intersection): {3,4,5}
CollectionUtils.disjunction(a, b)(Complement of intersection): {1,2,3,4,6,7}
CollectionUtils.disjunction(b, a)(Complement of intersection): {1,2,3,4,6,7}
CollectionUtils.subtract(a, b)(A And B Poor): {1,2,3}
CollectionUtils.subtract(b, a)(B And A Poor): {4,6,7}

 

 

Posted by slimboy007 on Fri, 08 Oct 2021 23:08:32 -0700