Write code with these ideas, my colleagues will not think you are a programmer to copy and paste

Foreword

Recently finished version of the demand in December, there are not deep enough to think of the code, write to sum up, I hope you write code daily multi-thinking, multi-point summary, come on! At the same time, where there is something wrong, but also pointed out that hope.

First, the complex logic conditions, can adjust the order, make it more efficient procedures.

Assuming that business demand is this: members, landed for the first time, you need to send a thank you notes. If they do not think, write the code directly

if(isUserVip && isFirstLogin){
    sendMsg();
}
复制代码

Assuming a total of five requests, isUserVip there are three requests by, isFirstLogin 1 through request. So the above code, the number is five isUserVip performed, the number of times is three times isFirstLogin performed as follows:

If the order isUserVip and isFirstLogin adjustments about it?

if(isFirstLogin && isUserVip ){
    sendMsg();
}
复制代码

IsFirstLogin execution times is 5 times, the number of times is 1 isUserVip performed as follows:

Jiang Zi whether your program more efficient it?

Second, your program is unnecessary objects inadvertently created.

For chestnut, determine whether the user is in the membership period, usually similar to the following codes:

//判断用户会员是否在有效期
public boolean isUserVIPValid() {
  Date now = new Date();
  Calendar gmtCal = Calendar.getInstance();
  gmtCal.set(2019, Calendar.JANUARY, 1, 0, 0, 0);
  Date beginTime = gmtCal.getTime();
  gmtCal.set(2020, Calendar.JANUARY, 1, 0, 0, 0);
  Date endTime= gmtCal.getTime();
  return now.compareTo(beginTime) >= 0 && now.compareTo(endTime) <= 0;
}

复制代码

But then, each call isUserVIPValid method creates Calendar, and Date objects. In fact it, in addition to New Date, other objects are the same, we can extract a global variable , to avoid creating unnecessary objects , thereby improving the efficiency of the program, as follows:

public class Test {

    private static final Date BEGIN_TIME;
    private static final Date END_TIME;
    static {
        Calendar gmtCal = Calendar.getInstance();
        gmtCal.set(2019, Calendar.JANUARY, 1, 0, 0, 0);
        BEGIN_TIME = gmtCal.getTime();
        gmtCal.set(2020, Calendar.JANUARY, 1, 0, 0, 0);
        END_TIME = gmtCal.getTime();
    }

    //判断用户会员是否在有效期
    public boolean isUserVIPValid() {
        Date now = new Date();
        return now.compareTo(BEGIN_TIME) >= 0 && now.compareTo(END_TIME) <= 0;
    }
}
复制代码

Third, when you query the database, you have no more than check the data?

As we all know, check the library is more time-consuming operation, especially when large volumes of data. Therefore, the query DB, like we needed to take, there is no need to blanket.

Assuming that business scenario is this: whether a user is a member of the query. Have seen implementation code is. . .

List<Long> userIds = sqlMap.queryList("select userId from user where vip=1");
boolean isVip = userIds.contains(userId);
复制代码

Why have found out first of all, and then determine whether to include this useId, useId to determine whether it is a member? UserId pass directly into sql, it does not smell? as follows:

Long userId = sqlMap.queryObject("select userId from user where userId='userId' and vip='1' ")
boolean isVip = userId!=null;
复制代码

In fact, apart from the query are passed in the past, check the database to avoid redundant data back, you can also select specific fields in place select *, making the program more efficient.

Fourth, add a line of code notification class, can not affect the main flow of it.

Business Process assume this: when the user needs to log in to add a text message to inform its fans. It is easy to think of the implementation process is as follows:

Assumptions offers sendMsgNotify services system hung up , or call sendMsgNotify fails , then the user login failed. . .

A notification function leads to the main landing procedure is not available, obviously penny wise and pound foolish. Then there is no way to fish eat it too? Yes, texting interfaces to capture exception handling , or open another thread asynchronous processing , as follows:

Therefore, we add notification class and so not a non-major, when downgrade interface, should stop and consider whether it will affect the main flow, thinking how best to deal with.

V. holding olfactory null pointer, such as the use equals the comparison, determining the value of constant release or left.

NullPointException long been commonplace in the Java world, when we write code, you can think twice before they write, try to avoid low-level null pointer issues.

For example, the following business scenarios, to determine whether the user is a member, we can often see the following code:

boolean isVip = user.getUserFlag().equals("1");
复制代码

If you let this line of code on a production environment, to be king when I look back, it may be that a null pointer bug, in the dim light. Obviously, this may cause a null pointer exception because user.getUserFlag () may be null.

How to avoid null pointer problem? The constant 1 into the left can be friends, as follows:

boolean isVip = "1".equals(user.getUserFlag());
复制代码

Sixth, your business-critical code has a log escort?

The key business code wherever, should have sufficient log escort.

For example: you achieve transfer business, turn a few million, then turn failed, then customer complaints, then you have not printed to the log, think about the plight of the kind of dire straits, but you do nothing . . .

So, your transfer business will need those logs it? At least, before the method is called, the parameters need to print it needs, the interface calls, you need to capture abnormal about it, and print it related to abnormal log, as follows:

public void transfer(TransferDTO transferDTO){
    log.info("invoke tranfer begin");
    //打印入参
    log.info("invoke tranfer,paramters:{}",transferDTO);
    try {
      res=  transferService.transfer(transferDTO);
    }catch(Exception e){
     log.error("transfer fail,cifno:{},account:{}",transferDTO.getCifno(),
     transferDTO.getaccount())
     log.error("transfer fail,exception:{}",e);
    }
    log.info("invoke tranfer end");
    }
复制代码

In addition to print enough logs, we also need to note is that the log level do not confuse use , do not print this info to the log, but you printed error level, alarm reminders you up late at night to troubleshoot problems on the bad.

Seven, the number of rows for more functions, can be divided into small functions whether to optimize it?

When we maintain old code, often see a Tuotuo code, some function hundreds of lines or even thousands of lines , read them more difficult.

Suppose now have the following code

public class Test {
    private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {
        //print banner
        System.out.println("****************");
        System.out.println("*****customer Owes *****");
        System.out.println("****************");

        //calculate totalAmount
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while (env.hasMoreElements()) {
            Order order = (Order) env.nextElement();
            totalAmount += order.getAmout();
        }

        //print details
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }
}
复制代码

Divided into small, single-function after the function:

public class Test {
    private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {

        //print banner
        printBanner();
        //calculate totalAmount
        double totalAmount = getTotalAmount();
        //print details
        printDetail(totalAmount);
    }

    void printBanner(){
        System.out.println("****************");
        System.out.println("*****customer Owes *****");
        System.out.println("****************");
    }

    double getTotalAmount(){
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while (env.hasMoreElements()) {
            Order order = (Order) env.nextElement();
            totalAmount += order.getAmout();
        }
        return totalAmount;
    }

    void printDetail(double totalAmount){
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }
    
}
复制代码

A too lengthy function or some comment is required in order to make people understand the code use, consider cutting it into a function unit features a clear, brief and clearly defined function name, this will make the code more elegant.

Eight, some variables, such as red skin and so on, to make the configuration of whether it would be better.

If demand for products raised a red envelope, Christmas, Christmas red skin related, Spring Festival, red skin and so on.

If you write the code to control the dead, there can be similar to the following code:

if(duringChristmas){
   img = redPacketChristmasSkin;
}else if(duringSpringFestival){
   img =  redSpringFestivalSkin;
}
......
复制代码

If at the Lantern Festival, when suddenly another little sister operation idea, red lanterns into the skin-related, this time, is not going to modify the code, and re-released?

From the outset, to achieve a configuration table red skin, red skin will make the configuration of it? Replace the red skin, just modify the table data just fine.

Nine, the excess import category, local variables, no reference is not to be deleted

If the code is seen that there is no import class used, not being used to the local variables, etc., to delete it, the following:

These are not referenced local variables, if not used to it, uninstall it, it is not a vintage Nver, will keep more mellow. It will still be compiled together, that it is Haozhe resources yet.

Ten, when querying large table, whether to raise the index, you go sql index thing.

Query large amount of data tables, we need to confirm three things:

  • Your table is built index
  • Your sql query whether the index hit
  • Are your sql there is room for optimization

In general, the amount of data more than 100,000 tables, consider adding an index to the table. Under what circumstances, the index will fail it? like a wildcard, such as computing the index column index will lead to failure. Interested friends can look at my article. The necessary back-end programmers: the failure of the index's top ten diseases

XI, your method should return an empty set or null in the end it?

If it returns null, the caller forget to detect when might throw a null pointer exception. It returns an empty set, it eliminates the problem.

When mybatis query, if it returns a set of results is empty also returns an empty set, rather than null.

Positive example

public static List<UserResult> getUserResultList(){
    return Collections.EMPTY_LIST;
}
复制代码

Twelve, try to specify the size of the set of initialization

Ali recommended that development manual

Assuming that the number of elements of the map that you want to store about 15, and most worded as follows

 //initialCapacity = 15/0.75+1=21
 Map map = new HashMap(21);
复制代码

XIII, query the database, if the data returned too many, considering batches.

Suppose your table has 100,000 orders data to update the state, not a one-time queries all the orders are not updated in batches.

Counterexample:

List<Order> list = sqlMap.queryList("select * from Order where status='0'");
for(Order order:list){
  order.setStatus(1);
  sqlMap.update(order);  
}
复制代码

Positive examples:

Integer count = sqlMap.queryCount(select count(1) from Order where status ='0');
while(true){
    int size=sqlMap.batchUpdate(params);
    if(size<500){
        break;
    }
}
复制代码

Fourth, if you take into account the interface idempotency, complicated situation?

What sex is power and so on? Once and repeatedly requests a resource for a resource in itself should have the same result. That is, any of its multiple executions were carried out with the same impact once the impact generated by the resource itself right.

Why do we need Idempotence?

  • The user clicks on a number of consecutive APP submitting an order, you can not generate more orders
  • Users because the network card, the continuous click to send a message, the recipient can not receive repeated the same news.

Suppose there are business scenarios:

Users click on the download button, the system begins to download the file, click again to download the user will be prompted to download a file being.

There are some people would realize this:

Integer count = sqlMap.selectCount("select count(1) from excel where state=1");
if(count<=0){
    Excel.setStatus(1);
    updateExcelStatus();
    downLoadExcel();
}else{
    "文件正在下载中"
}
复制代码

We can look at what problems there may be two requests come?

Implementation process:

  • The first step, A query file is not downloaded in.
  • The second step, B query file is not downloaded in.
  • The third step, A to start downloading the file
  • Part IV, B start downloading the file

Obviously, it is a problem, while two files to download. Proper implementation of it?

if(updateExcelStatus(1){
    downLoadExcel(); 
}else{
    "文件正在下载中"
}
复制代码

Fifth, strengthen your tools with a private constructor, this does not Miya?

Methodological tools class are static methods, can be directly invoked by class. But some callers may first instantiation, then subject to call, and this is not good. How to avoid this situation, let your tools to reach the state controlled it, add a private constructor

public class StringUtis{
       private StringUtis(){} ///私有构造类,防止意外实例出现
       public static bool validataString(String str){
           
       }
}
复制代码

XVI basically unchanged user data, cached, the performance whether it has improved

Suppose you need to query interface to the database many times to get to each of the data, and then the various sorting operations, etc. Based on these data, this series of fierce like a tiger down the operation, interface performance was not good enough. Typical application scenarios such as: live list of these.

So, how to optimize it? Analysis of portions of the data you sort of real-time change data, continue to check the DB, the same data, such as the age of the user, put forward a scheduled task, take them to pull from DB cache, go directly to the cache.

So, think about this point is that, in the proper timing, the proper use of caching.

To be added...

Personal Public Number

  • If you are a love of learning boy, I can focus on the public number, learning together discussion.
  • What if you feel that this article is not the right place, can comment, I can also concerned about the number of public, private chat me, we will study together progress Kazakhstan.

Guess you like

Origin juejin.im/post/5dfe2e72518825125f39a2de