Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Cover: Autumn in school

Background: The reason for writing this is also what I happened to see in these two days. Although I have always had the Java development manual of Alibaba and have seen it many times, I have not paid attention to this problem 😂

Of those who have seen, but not all of 👰

Let’s have a look at the blunt 🏂

HXDM, I can not write a small story 😭, but can see in my writing a lot, still calculate practical share, give a praise 👍 ah.

Here please XDM drink 🥤

1. Preface 🚕

Today, when I was writing a AdvertVO class, I directly gave a long with ID, without using the packaging type. Then the Alibaba Java Coding Guidelines plug-in in IDEA directly gave a yellow wavy line, ALT+ENTER. The note in the Alibaba Java Development manual says:

The criteria for using basic and wrapped data types are as follows: 1) All POJO class attributes must use wrapped data types. 2) The return values and parameters of RPC methods must use wrapper data types. 3) Basic data types are recommended for all local variables.

Note: The absence of initial values for POJO class attributes reminds users that they must explicitly assign values when they need to use them. Any NPE problems, or entry checks, are guaranteed by the user.

When I just read, a little bit did not fully understand this meaning (may be MY dish, have not experienced such a scene), and then in order to understand their own hearts of small doubts 😂, 👇

So let’s do a simple example to understand that, and then we’ll talk about what actually happens, and the harm that can happen

2. Examples 🛵

public class Main {
    private static Integer a1;
    private static int a2;

    private static Boolean b1;
    private static boolean b2;
  
    public static void main(String[] args) {
        System.out.println("Integer ==> a1:"+a1);
        System.out.println("int ==> a2:"+a2);
        System.out.println("Boolean ==> b1:"+b1);
        System.out.println("boolean ==> b2:"+b2);
    }
    /** * Result: * Integer ==> A1 :null * int ==> A2 :0 * Boolean ==> B1 :null * Boolean ==> B2 :false */
}
Copy the code

All wrapper types default to null when we don’t assign values, whereas primitive types always initialize a default value.

Boolean is false, byte, short, int, long is 0, float is 0.0f, and so on.

👨💻 XDM may have noticed, but not fully noticed, the difference between using basic types and packaging types. Here’s a scenario to illustrate the difference: 👩🏫

3. Scenario 🛫

[Example] : The query result of the database may be null, because automatic unpacking, using the basic data type to receive NPE risk. (NPE explained below)

[Counterexample] : The transaction report of a certain business shows the rise and fall of the total transaction amount, that is, plus or minus X %. X is the basic data type and the RPC service is called. When the call fails, the default value is returned and the page displays 0%, which is unreasonable and should be displayed as a dash -. So the null value of the wrapper data type can indicate additional information, such as: remote call failure, abnormal exit.

1) Scenario 1 ⛵

As another example of a deductible, we are building a deductible system that requires reading a rate value from an external pricing system. We expect the return value of this interface to contain a floating point rate field. When we get this value, we use the formula: amount * rate = cost to calculate, and the calculation results are deducted.

If the billing system is abnormal, it may return a default value of null if the field is a Double or 0.0 if the field is a Double.

If the fee deduction system does not do special treatment for the rate return value, get null value for calculation will directly report an error, block the program. Get 0.0 May be directly calculated, the interface is 0 after deduction. The anomaly can’t be detected.

Some people say, “I can make a special judgment on 0.0, if it is 0 can block the error ah. However, a question arises at this point, what if the allowed rate is zero? (As follows)

One small conclusion: Using basic types may increase the complexity of the system to a certain extent, causing more and more pits. There is also the use of wrapper types to define variables that block application execution with exceptions so that online problems can be immediately identified. However, if we use basic data types, the system may assume there is no exception and continue to run. It’s only passive testing, and even more so if it’s online, I think it’s probably… All understood.

2) Scenario 2 🌆

If we have a custom Student class, one of the attributes is grade score.

If you define an exam with an Integer instead of an int, the student might not have taken it and the value would be null, or they might have taken it and got a zero, and the value would be zero.

public class Student  {

    private  Integer score;

    private  int score;
}
Copy the code

Notice that the states of these two expressions are obviously different. If we use the wrapper type, null means no test, 0 means 0 score; But if we use the primitive type, the two cases are indistinguishable.

4. NPE problem 🗽

【 Recommended 】 Preventing NPE is a basic training for programmers. Pay attention to the scenarios where NPE is generated:

NPE, which means returning null values for basic types of data, prevents NPE from being a basic rest for programmers. All NPE scenarios:

  1. If the return type is basic data type, automatic unpacking may generate AN NPE.

    public int f(a) {
          returnAn Integer object; } if fornull, automatically unpack and throw NPE.Copy the code
  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.

Example: Use JDK8’s Optional class to prevent NPE problems. Learn about the 👉JDK8 Optional class

Five, talk to yourself 🚏

Hello, THIS is blogger Ning Zaichun: homepage

I hope you found this article useful!!

Wish us: by the time we meet on another day, we have achieved something.

Welcome to discuss the question 😁, lie down 🛌

Reference: Alibaba Java Development Manual