Suggestions for a few friendly java code writing habits

I have worked for many years and met all kinds of colleagues. I have seen all kinds of code, excellent, rubbish, unattractive, etc. This article records some personal code development habits.

1. Encapsulation method parameters

When your method has too many parameters, it is recommended to encapsulate an object. The following is a negative teaching material. Who taught you to write such code?

public void updateX(long num, String str1, String str2, 
                    String str3, String str4,
                    String str5, String str6) {
    
    }

Try to encapsulate these outputs into an object

public class X {
    
    
    private Long num;
    private String str1;
    ...
}

Why do you write like this? For example, your method is for query. If you add query conditions later, do you need to modify the method? The method parameter list has to be changed every time it is added. Encapsulate an object, no matter how many query conditions are added in the future, you only need to add fields to the object. The point is that the code looks comfortable too!

2. Encapsulate business logic

If you have seen "Shit Mountain", you will feel deeply. Such a method can write thousands of lines of code, and there are no rules at all. Often the person in charge will say that this business is too complicated and there is no way to improve it, which is an excuse for being lazy. No matter how complex the business is, we can improve the readability of the code through reasonable design and packaging. Below is a suggested code.

@Transactional
public void clearBills(Long customerId) {
    
    
    //获取清算所需的票据ng
    ClearContext context = getClearContext(customerId);
    // 验证该金额是否合法
    checkAmount(context);
    // 确定优惠券是否可用,并返回可扣除金额
    CouponDeductibleResponse deductibleResponse = couponDeducted(context);
    // 结清所有账单
    DepositClearResponse response = clearBills(context);
    // 发送还款对账消息
    repaymentService.sendVerifyBillMessage(customerId, context.getDeposit());
    // 更新帐户余额
    accountService.clear(context, response);
    // 处理已清算的息票,用完或未绑定
    couponService.clear(deductibleResponse);
    // 保存优惠券扣减记录
    clearCouponDeductService.add(context, deductibleResponse);
}

The business in this code is very complex. It is estimated that 10,000 things have been conservatively done internally, but the things written by people at different levels are completely different. I have to praise the split of this business and the encapsulation of the method. There are multiple small businesses within a large business. Different businesses can call different service methods.

The person who takes over can quickly understand the business even if there are no relevant documents such as flow charts. Many business methods written by primary development are the first line of code for business A, the next line of code for business B, and the next line of code for business A. There is also a bunch of unit logic nested and called between businesses, which is very messy and a lot of code.

3. The correct way to judge that the collection type is not empty

Many people like to write code like this to judge collections

if (list == null || list.size() == 0) {
    
    
  return null;
}

Of course, if you insist on writing like this, there is no problem.
org.springframework.util.CollectionUtils But don’t you feel uncomfortable, any jar package in the framework now has a collection tool class, such as com.baomidou.mybatisplus.core.toolkit.CollectionUtils. Please write like this in the future

if (CollectionUtils.isEmpty(list)) {
    
    
  return null;
}

4. Collection type return value does not return null

When your business method returns a collection type, please do not return null, the correct operation is to return an empty collection. Take a look at the list query of mybatis. If no elements are queried, it will return an empty collection instead of null. Otherwise, the caller must make a NULL judgment, and the same is true for objects in most cases.

5. It is recommended to use lombok

Of course, this is a moot point, and my habit is to use it to omit getters, setters, toString, etc. Use Lombok

6. Write as few tools as possible

Why write less tool classes, because most of the tool classes you write are included in the jar package you import, such as String, Assert assertion, IO upload file, copy stream, Bigdecimal] and so on. It's easy to write your own bugs and load redundant classes.

7. Write meaningful method comments

Is writing this kind of comment afraid that the person who will take over later will be blind.

Either don't write it, or just add a description after it. It's a pain to write comments like this and get a bunch of warnings from IDEA

/**
* 请求号码验证
*
* @param a
* @param b
* @param param
* @return Result
*/

8. Try not to let IDEA call the police

Very disgusted to see a series of warnings in the IDEA code window, very uncomfortable. Because there are warnings, the code can be optimized, or there is a problem. A few days ago, I found a small bug in Teams. It has nothing to do with me, it's just that my colleagues are watching the business outside and judging why the business is wrong. I glanced at the question.

Because the integer literals int in java are of type, they become a set of Integer, and then click it stepId is a long type, and Long is in the set, then this contains returns false correctly, it is not a type.

You see, if you pay attention to the warning, you can move the mouse over it to see the hint, and there will be one less production bug.

9. Use new technical components as much as possible

I think this is the quality that a programmer should have. Anyway, I like to use new technology components, because the emergence of new technology components is to solve the shortcomings of old technology components, and as technicians, we should keep pace with the times.

Of course, the premise is to be prepared, not to upgrade for granted. Java 17 has released the simplest example, and new projects still use Date to handle DateTime.

in conclusion

The above are some of my personal views, please point out if there are any deficiencies.

Guess you like

Origin blog.csdn.net/stone1290/article/details/126270421