Read the "code clean way" summary

 Long read, "clean the Road Code" (in English Clean Code), when the blogger is a Sentimental rookie, is creating chaos code for the team. Years of work, the code has been repeatedly miserable pit of others, remembering the code when I left, certainly hurt later colleagues. When reading the JDK source code or other great open source projects, the building of admiration sophisticated code, they have a common characteristic: the exact variable name, just the right design patterns, rather than go into detailed notes and so on. Now re-read the book, summarize the content and add some of their own ideas to share with you.

Team communication code

 Communication work, not just e-mail or face to face verbal communication, the code is one way to communicate. Implementation requirements in code, just the first step in the Long March, the code must be allowed to express their design ideas. Imagine that you are responsible for the function of another colleague to take over, if your code structure clear and reasonable comments, he would not frequent challenge code doubt, do not interrupt your work. When writing code, should take into account other people's reading experience, reduce dyslexia, create the code for the entire team, not yourself.

Let campsite cleaner than when to

 This is the proverbial Boy Scouts of America regulations, the equivalent of the Boy Scouts of America Youth Summer Camp quasi-military management. After the summer camp children to leave the camp to clean up neat and clean, much cleaner than let the camp be. In the software development process, as it can be understood 不要破坏规则,不要引入混乱. If the team has developed a code specifications, such as the class name must have Subsystem prefix such as BiOrderService(Bi BI refers to business), it continues to follow down; another example, the team has provided the MD5 encryption such as public libraries, do not introduce new again the MD5 library. Many novice programmers followed by the job, do not like to see the specifications on the drawing board, we need some tools do not ask older drivers have no public library, introduced directly into the familiar library, causing compatibility or other issues.

Proper name

 Suitable naming is a priority, as a good name to the newborn as important. Naming is often inappropriate 词不达意、误导观众、过度缩写, etc., because English is not our mother tongue, to find a suitable word name seem really hard. My advice is to first figure out the business, organizational meetings set of words commonly used in business areas, prohibit members their invention. For example, using the code canteenrepresents the canteen, then do not re-invention DinnerHall, both long-winded and misleading colleagues.

Look at counter-example:
// 手机号
String phone = “13421800409”;
// 获取地址
private String getDiZhi();
//修改密码
private void modifyPassword(String password1 ,String password2)
Look at positive examples:
// 手机号 mobileNo比phone更精确
String mobileNo= “13421800409”;

// 避免英文拼音混杂
private String getAddress();

// 参数的命名要区分意义
private void modifyPassword(String oldPassowrd,String newPassword)

Short way

  How short is not conclusive method is appropriate, but a method of up to 500 lines, never let readers homicides heart. The method is too long, so that the reader does not know where to begin, forget looked back in front. Complex method, relatively simple logic split into short methods.

Look at counter-example:
//  获取个人信息
Private UserDTO getUserDTO(Integer userId)
{
    //获取基本信息 
    … 此处写了10行

    //获取最近的一次订单信息
    …  此处写了30行

   // 获取钱包余额、可用优惠券张数等
    ...   此处写了30行

   return userDTO;
}
Look at positive examples:
//  获取个人信息
Private UserDTO getUserDTO(Integer userId)
{
    //获取基本信息 
    UserDTO userDTO= getUserBasicInfo(userId);

    //获取最近的一次订单信息
    userDTO.setUserLastOrder(getUserLastOrder(userId));

    // 获取钱包、可用优惠券张数等
    userDTO.setUserAccount(getUserAccount(userId));  
    return userDTO;
}

Private  UserDTO getUserBasicInfo(userId);
Private  UserLastOrder getUserLastOrder(userId);
Private  UserAccount getUserAccount(userId);

Reduced if / else nested

  Why reduce nesting, it does not look nested fashion it? I once saw a colleague a piece of code nested up to 9 layers of his own to go when they are looking to maintain dizzy. Code excessive nesting result is that only the author can be read, then set Xia bewildered.

Look at counter-example:
// 修改用户密码,这个例子只有3层嵌套,很温柔了
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)
         }
    }
      }
}
Look at positive examples:
// 修改用户密码 
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);
}

Positive cases were reduced nesting guard statement, but not all are suitable for such scenes rewritten. If not, the logic high relevance may be extracted as an independent method for reducing nesting.

Detached try / catch

  We have not seen a long way from start to finish by a try / catch to take care of? Project bloggers experienced, this wording is not responsible abound. Not every line of code will throw an error, the error will be thrown as long as the business can be placed in a separate method.

Look at counter-example:
//  获取个人信息
Private UserDTO getUserDTO(Integer userId)
{
   try { 
       //获取基本信息 
       ... 此处写了10行
       //获取最近的一次订单信息.
       ...此处写了20行
       // 获取钱包、可用优惠券张数等
       ...此处写了20行
    }catch (Exception e) {
        logger.error(e);
        return null;
    }
}
   return userDTO;
}
Look at positive examples:
//  获取个人信息
Private UserDTO getUserDTO(Integer userId)
{
    //获取基本信息 
    UserDTO userDTO= getUserBasicInfo(userId);

    //获取最近的一次订单信息
    userDTO.setUserLastOrder(getUserLastOrder(userId));

    // 获取钱包、可用优惠券张数等
    userDTO.setUserAccount(getUserAccount(userId));  
    return userDTO;
}
Private  UserDTO getUserBasicInfo(userId);
Private  UserLastOrder getUserLastOrder(userId);
Private  UserAccount getUserAccount(userId){
      try{ // TODO } catch( Exception e) { //TODO}
}

Packaging a plurality of parameters

 If the method parameters over three to put the proposal wrap up the class, or else to add parameters, due to the strong coupling will lead to semantic caller syntax error. Paging query interface in the background management, there are often a lot of query parameters, and are likely to increase, it is the best package.

Look at counter-example:
// 分页查询订单 6个参数
Public Page<Order> queryOrderByPage(Integer current,Integer size,String productName,Integer userId,Date startTime,Date endTime,Bigdecimal minAmount ,Bigdecimal maxAmount) {

}
Look at positive examples:
@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个参数
Public Page<Order> queryOrderByPage(OrderQueryDTO orderQueryDTO) {

}

Third-party libraries

chilli

Lombok assembly by way of annotation, at compile time automatically generated constructor property, getter / setter, equals, hashcode , toString methods
for example as follows:
@Setter or field-based annotation, the annotation generating setter methods for all fields in the class, comment generating setter method for the field when the field only.
@Getter use as above, except that the getter is generated.
@ToString notes in class, adding toString method.
@EqualsAndHashCode annotation type, and equals generating hashCode method.
@NoArgsConstructor annotation class, generating a constructor with no arguments.
@RequiredArgsConstructor annotation class constructor method for a field generating class require special handling, such as final and the @NonNull annotated field.
@AllArgsConstructor annotation class, generates a class constructor all fields.
@Data annotation type, setter / getter, equals, canEqual , hashCode, toString method, such as the final attribute, the attribute is not generated setter method for the generation.

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

    public void setUserId(Integer userId) {
          return this.userId = userId; 
 }
}
The use of Lombok:
@Getter
@Setter
Public class Order {
     private Integer userId;
}

Apache Commons Series

  Apache Commons components provides us with a series of tools methods strings, collections, IO operation on. These components are a big treasure, provided a lot of wheels.

Package Introduction
beanUtils JavaBean various operations, clone, properties, etc.
codec A method of processing commonly used encoding tools package, e.g. DES, SHA1, MD5, Base64 like.
collections java operating frame collection
configuration java application configuration management library
I io package tool
only Tools package base object methods, such as Java StringUtils, ArrayUtils like.
logging Log interface provided
net Providing verification data frame client and server
Look at an example:
例1: 判断集合是否为空:
CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false

例2: 判断集合是否不为空:
CollectionUtils.isNotEmpty(null): false
CollectionUtils.isNotEmpty(new ArrayList()): false
CollectionUtils.isNotEmpty({a,b}): true

例3:2个集合间的操作: 
集合a: {1,2,3,3,4,5}
集合b: {3,4,4,5,6,7}
CollectionUtils.union(a, b)(并集): {1,2,3,3,4,4,5,6,7}
CollectionUtils.intersection(a, b)(交集): {3,4,5}
CollectionUtils.disjunction(a, b)(交集的补集): {1,2,3,4,6,7}
CollectionUtils.disjunction(b, a)(交集的补集): {1,2,3,4,6,7}
CollectionUtils.subtract(a, b)(A与B的差): {1,2,3}
CollectionUtils.subtract(b, a)(B与A的差): {4,6,7}

Guess you like

Origin www.cnblogs.com/xiaoyangjia/p/11245235.html