The routine of refactoring the system - writing organized code

If a project experiences rapid development, it is bound to leave a very disordered and chaotic code behind the business development. The disordered and chaotic code is bound to cause a lot of bug fixes and expansion costs.

When it comes to building systems, we are talking about high concurrency, big data, and easy maintenance and scalability are left behind by most people. Adding the most basic object-oriented ideas and design patterns helps us organize code that is easy to maintain and read .

Don't look too high on things with high concurrency and high availability. Do the following basic things well. Your system will be doubled in readability, maintainability and extensibility, and everyone's human efficiency will be improved from every time. In the process of bug generation and code sorting, it is the architect's first task to establish standards and principles.

  • proper packaging
  • open closed principle
  • One can only principle
  • The code has the ability to delete at any time without affecting the context

Naming and Notes

Naming needs to be known by name, and comments can help us understand the business logic at that time, otherwise we can only locate the problem through line-by-line logs later.

Considering that the IDE will help us create variable names, if the names are similar, misuse may cause bugs that may be difficult to locate. The input parameters can end with Req or Command, and the return value can end with Resp or Result.

Pull out the business skeleton

The entry layer of the Web system is the Controller, and the RPC-based service entry layer is often XxxServiceImpl. The entry layer should be like the table of contents and preface of a book, explaining the main purpose of this method, and sorting out the core business processes. The process should not be too much. Thin or too thick, just to meet the needs of the product, the skeleton is mainly, it can be simply understood as the information abstraction of the product PRD.

Build the glue layer code

Large-scale systems or business systems have a certain degree of complexity, and it is bound to include some necessary large logic processing in some problem scenarios, so a glue layer code is established, and the glue class can be defined with a method name of the entry layer as the name. The public interface exposed by the glue layer code is the core skeleton logic of the entry layer, which encapsulates the internal complex logic, so that some methods can be deleted, commented out, and replaced at any time without affecting the effect of the core skeleton logic, which can be understood as TDD, just pay attention to the input parameters and return values. If there are certain dependencies with other systems through RPC or ResultAPI, put them here. In fact, this layer has some Domains in DDD, but if DDD is not used properly, it will cause problems that are difficult to control in the distributed microservice scenario.

Lower-level dependent code

Under the entry and business logic are basically the Service layer code and Dao layer code. Dao mainly deals with the storage system, and the main purpose is to switch to other storage logic at any time without affecting the upper-layer business and code. Service is a certain data structure organization. The data structure may come from the underlying Dao, may come from the subscription of the message queue, may come from Redis cache or Hbase, etc., at this layer can effectively separate the dependent system data and the system data .

Example

Enter image description

input

public class WmPoiReq { 
    private long userId; 
    private long wmPoiId; 
    private int channel; 
}

return result

public class WmPoiResp { 
} 

entity

public class Activity { 
    int activityId; 
    Long wmPoiId; 
    int channel; 
    long valida; 
}

Service entrance

public class CServiceImpl { 
 
    /** 
     * 发送积分
     * @param req 
     * @return 
     */ 
    public WmPoiResp wmPSendC(WmPoiReq req){ 
        // 入参不合法,及时失败 
        if(null == req || req.getUserId() < 1l || req.getPId() < 1l || req.getCh() < 0){ 
            throw new IllegalStateException("参数无效"); 
        } 
 
        PSendCHandler handler = new PSendCHandler(); 
        // 1. 获取可用列表 
        List<Activity> activities = handler.getActivityList(req.getPId(), req.getUserId(), req.getCh()); 
 
        // 2. 满足,进行发操作 
        boolean sendStatus = handler.sendC(req.getPId(), activities); 
 
        // 3. 调用接口服务化发
        // RPC调用服务发送 
 
        WmPoiResp resp = new WmPoiResp(); 
        return resp; 
    } 
}

Create glue code to implement process details

public class PSendCHandler { 
 
    /** 
     * 获取可用活动列表 
     * @param iId  
     * @param userId 用户id 
     * @param channel 
     * @return 
     */ 
    public List<Activity> getActivityList(long PiId, long userId, int channel){ 
        // 1. 根据PiId, channle获取活动列表 
        List<Activity> activities = ... // 假装从底层数据获取 
        if(activities.size() == 0) return new ArrayList<>(); 
 
        // 2. 判断获取是否已过期 
        boolean expire = activities.size() > 0 ? activities.get(0).getValida() > new Date().getTime() : true; 
        if(expire) return new ArrayList<>(); 
 
        // 3. 判断是否是新用户 
        boolean freshMan = ... // 假装从底层数据获取 
 
        if(freshMan){ // 新用户,验证是否有适用于新用户活动 
           Iterator<Activity> iterator = activities.iterator(); 
           while (iterator.hasNext()){ 
               // 检查每个activity是否适用于新用户 
           } 
           // 所有活动不适用于新用户 
            return new ArrayList<>(); 
        } 
 
        // 返回可用活动列表 
        return activities; 
    } 
 
    /** 
     * 发券 
     * @param PiId 门店id 
     * @param activities 活动集合 
     * @return 
     */ 
    public boolean sendC(long PiId, List<Activity> activities){ 
        // 通过线程池异步发 
        // 同时记录缓存 
        return true; 
    } 
}

Summarize

In fact, it is very simple to sum up, add the necessary encapsulation and extraction, and control it through input parameters and return values. Organize the code system with the thinking of reading books, and increase the readable and comprehensible ability of a business. After a certain stage of system development, the most troublesome thing for RD students is not technical problems, but often some business logic or pudding code. Therefore, R&D students should Consciously separate business and technology, rather than simply entangle technology and business, and do a good job of a piece of business logic code that can be deleted at any time without affecting the ability of the system. Establish proper code naming conventions to avoid unnecessary misuse of IDEs. Enrich wiki and documentation, involving test cases, database field documentation, product PRD, etc.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325621823&siteId=291194637