The author likes to talk

Hello, everyone, I am “Xingyun”

This is the 11th original article. I hope this article can give you some thinking and inspiration

Last week to accept a task scheduling is out, as a result of the development of database data, in the process of debugging, under the rules of I think the business data should not be empty, throw the NPE, was tortured to death, personal and use since its research framework, does not support hot deployment, module also many, every changes have to repack to start again, So let’s take a look at the familiar NPE and see if you really understand it and can avoid it perfectly.

Have you ever encountered an NPE?


Null-pointer exceptions are one of those bugs that developers are probably familiar with at some point

Accidentally, dropped the pit inside, and then say, right ah, forget, back to the code, quickly add a empty operation

Let’s talk about what a common NullPointerException is

  • What is NPE?
  • What are the actions that cause NPE?
  • What do I do? How do I avoid the damn NPE?

What is the NPE


A null pointer occurs when an application passes null when it needs an object.

  • Calls the instance method of a NULL object

  • Accesses or modifies the properties of a NULL object

  • Gets the length of the array whose value is null

  • When accessing or modifying a column of a two-dimensional array whose value is NULL

  • Null is thrown as a Throwable object

I understand that, so in actual Coding, what operations can cause NPE?

Damn NPE, there you are again

Open up the familiar handbook.

The manual says: Preventing NPE is the basic training of programmers, pay attention to the scenarios in which NPE occurs:

  1. If the return type is basic data type, automatic unpacking may generate AN NPE
  2. The database query result may be NULL.
  3. The element in the set, even if it’s isNotEmpty, can pull out data elements that are null
  4. When a remote call returns an object, null pointer detection is required to prevent NPE
  5. You are advised to perform AN NPE check on the data obtained in the Session to avoid null Pointers
  6. Cascade call obj.geta ().getb ().getc (); A series of calls, easy to generate NPE
  7. Object’s equals method is prone to null-pointer exceptions and should be called using constants or objects with determined values

Let’s take a look at some actual scenarios

Lin accepts a “wrapper object argument” A, then goes through a series of convoluted operations, and then “return basic datatype”, but if the argument passed in a is null, sorry, the null pointer will appear on your console

public int test(Integer a)  {
    // something code
    return a;
}
Copy the code

If loanReceiptDtoList is null, then the NPE will appear in the first place

Of course, suppose That Lin Budong found some iOU, but the iOU data is not complete, some of the iOU data do not have the customer’s name, then the second place will report NPE

public void lookReceipt(Condition condition) {
        List<LoanReceiptDto> loanReceiptDtoList = loanReceiptMapper.sqlect(condition);
        for(LoanReceiptDto loanReceiptDto : loanReceiptDtoList) {
            / / first place
            whoNoMoney(loanReceiptDto);
 }  }  private void whoNoMoney(LoanReceiptDto loanReceiptDto) {  / / in the second place  if(loanReceiptDto. GetCustomerName (.) the equals (small)) { System.out.println("This is Mei.");  }; } Copy the code

Lin accepts the hashMap sent by Xiaomei, but he simply determines whether the element size is 0, but assuming that xiaomei sends in (“k”, null), the fetched value is still null

public void test(HashMap<String, String> hashMap) {
    // This result is true
    isNotEmpty(hashMap);
}
Copy the code

Lin Budong wants to judge whether the client name of this iOU is Mei. Is it right to write this? Of course not. The positive example should be to reverse the equals call, and Amy should be the caller to “equals()”, not the argument. Your caller should “call equals using constants or objects with certain values.” of course, “java.util.Objects#equals(Object a, Object b)” introduced in JDK7 is also very nice

public void test(a) {
    LoanReceiptDto loanReceiptDto = new LoanReceiptDto();
    // Small beauty is magic value, not recommended, here for example
    if (loanReceiptDto.getCustomerName().equals("Little beauty")) {
        // something code
 } } Copy the code

Let’s share an example of a fancy pit step

// We, as consumers, invoke the following two-party service interface
public Boolean someRemoteCall(a);

// Return TRUE or FALSE, and use it as a criterion or as a base type. If null is returned, the null pointer will be raised:
if (someRemoteCall()) {
 // something code  } Copy the code

When you look at the example, you may think it is very simple, but in the actual development, you will often ignore some scenarios to think about whether there is NPE, I hope you Code and be careful

How to avoid NPE

(To illustrate real usability, try to take screenshots from the project code.)

1. Use Optional

Optional is a feature introduced in Java 8. Returning an Optional explicitly tells the user that the result may be null:


2. Secondly, learn from section 7.8 of Code Brevity: “Do not pass null values”.

Defensive parameter detection, one of the most common methods, can greatly reduce the probability of error and improve the robustness of the program


3. Use lombok’s @nonnull annotation


4. Return the empty collection

Returns the empty collection if the parameters are not appropriate

5. Use Objects

You can use the Objects class introduced in Java 7 to simplify the code for nulling and throwing null Pointers.

Here you can also use some tool kits for judgment processing, a recommendation, I hope you can pay attention to the harm that NPE brings to the program robustness


I am “xingyun”, point a praise to walk again, we next period goodbye 👋