Programming habits: Why do we need to make non-empty, not equal to 0...judgments, the difference between null and 0

1 Null value, what types are not equal to zero

1.1 Common data types correspond to values ​​that need to be judged

insert image description here

1.1 Basic data types

Note : The 8 basic data types of java only have the judgment of not being equal to 0, and there is no judgment of non-empty (null) . Because the value range of the basic type does not contain null.

Default value :

  1. The default value of integer type int, byte, short, long: 0
  2. The default value of float and double with a decimal point is: 0.0
  3. The default value of boolean is: false
  4. The default value of char is: /u0000(the default value, generally not displayed. The code of the blank character is 0x20, and the code below 0x20 is an invisible control character. Some systems will output a box when encountering an invisible character to indicate that an invisible character is encountered )

The meaning of the non-zero judgment of the basic type : 数据是否被有效赋值的判断在很多情况下也是必要的.

1.2 Reference data types

Default : null

The significance of the non-null judgment of the reference type : 防止出现空指针异常, when we call the method of this unassigned variable, or access its internal variables, a null pointer exception will be thrown.

1.2.1 String (difference between null and 0)

Note : Although the String type is also a reference type, it needs to be judged to be not equal to 0 or not to be empty (null).

The difference between 0 and null in an object:

Objext ob = new Object();
ob = null; //对象为空,连地址值都没有
ob = 0//有对象地址值,但是存的值为0

Default : null

Significance : Non-empty judgment prevents the occurrence of null pointers, and the length is greater than 0 to avoid being an empty string""

//注意:这种写法 s == null是必要且必须在前面的,否则会因为null调用方法而抛出空指针异常。
if(s == null || s.length() <= 0){
    
    ......} //s是一个String类型

1.3 Container class

1.3.1. Array

Default value :

  1. declares but does not define length, value is null
  2. Array with length 0, not null, but be careful not to take out elements directly, an index out of bounds error (ArrayIndexOutOfBoundsException) will be thrown
  3. The basic type array is declared and the length is defined, but no value is assigned, and all element values ​​are the default value of the basic type
  4. The reference type array is declared and has a defined length, but no value is assigned, and all elements are null
    int[] arrayNull;  //值为null
    int[] arrayZero = new int[0]; //值为{}
    int[] arrayInt = new int[2];  //值为{0,0}
    Object[] arrayObj = new Object[2];  //值为{null,null}

Description : It can be judged that it is not empty and the length is not equal to 0

The difference between null and 0? ? ?

1.3.2. Collection

  1. null if not assigned
  2. List: Duplicate elements are allowed, and any number of nulls can be added.
  3. Set: Duplicate elements are not allowed, and at most one null can be added.
  4. Map: The key of the Map can add at most one null, and the value field has no limit.

Description : Non-empty judgment can be made.

2. Why do empty judgments

Description: Make the program robust and defensive

2.1. Avoid Null Pointer Exceptions

In the case of defining a variable without assigning a value, except for basic data types, other types of variables will default to null.
Null can also be considered as the default value of other types except basic data types, so a method with parameters, as long as the parameter is not a basic data type, can be filled with null as a parameter when calling.

public void funcString(String s) {
    
    
    s.isEmpty();
  }

 //在main方法中调用
funcString(null);      //参数传入null  IDE并不会报错 可以进行编译

//运行后会抛出NullPointerException

It can be seen that null is passed into the method as a parameter, but once null is passed in, the internal process is equivalent to null.isEmpty(); it is normal to report an error.
Therefore, it is very necessary to add a non-null judgment to the situation where a method call to an object method is required.
Let's take a more practical example:

Suppose the server returns such a piece of json data

{
    
    
        "id": 5,
        "title": "我是文章标题",
        "comment": {
    
    
            "userid": 4,
            "content": "我是评论内容~~~"
        }
    }

Now map it to an object like this

public class Article {
    
    
  
  private int id; //文章id
  private String title;//文章标题
  private Comment comment;//文章评论

  class Comment {
    
    
    //内部对象“评论”
    private int userId;//评论用户Id
    private String content;//评论内容

    public int getUserId() {
    
    
      return userId;
    }

    public void setUserId(int userId) {
    
    
      this.userId = userId;
    }

    public String getContent() {
    
    
      return content;
    }

    public void setContent(String content) {
    
    
      this.content = content;
    }
  }

  public int getId() {
    
    
    return id;
  }

  public void setId(int id) {
    
    
    this.id = id;
  }

  public String getTitle() {
    
    
    return title;
  }

  public void setTitle(String title) {
    
    
    this.title = title;
  }

  public Comment getComment() {
    
    
    return comment;
  }

  public void setComment(Comment comment) {
    
    
    this.comment = comment;
  }
}

Taking TextView, the most basic control of Android, as an example, we now display the content of article comments

protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.txt);
    String commentContent=getArticle().getComment().getContent();
    textView.setText(commentContent);
  }

public Article getArticle(){
    
    
    //获取数据 映射成Article对象 并返回
  }

The above example does not add a non-empty judgment, and the comments on the article are displayed smoothly.
However, if a newly published article may not be seen by many people, how can there be comments? The data returned by the server is likely to be like this:

{
    
    
        "id": 6,
        "title": "我是文章标题",
        "comment": {
    
       
        }
    }

At this time this code

 String commentContent=getArticle().getComment().getContent();

At runtime it becomes

String commentContent=null.getContent();

Therefore, a non-null judgment must be added:

protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.txt);
    if (getArticle().getComment()!=null){
    
    
    String commentContent=getArticle().getComment().getContent();
    textView.setText(commentContent);
    }
  }

2.2. Increase program performance

In the same example as above, this code

 String commentContent=getArticle().getComment().getContent();

You can also use the try catch statement to catch the null pointer exception and handle it.
But through the non-null judgment method, when the program runs to if (getArticle().getComment()!=null), it will not continue. From the perspective of performance It is more appropriate to say.

3. Use return to reduce nesting

When using non-empty judgments, because of the use of if–else statements, it is inevitable to have more nesting. When the logic is relatively simple, it is okay. If the logic is more complicated, multiple nesting may be used. Looking at a bunch The indentation affects the readability of the code, so it is very important to develop the habit of using return statements to reduce nesting from an early age.

Continue to optimize the above code:

protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.txt);
    if (getArticle().getComment() == null) return; //把判断条件改为相反 一旦符合return结束方法
    String commentContent = getArticle().getComment().getContent();
    textView.setText(commentContent);
  }

A pair of curly braces are missing after using return. In this example, there may not be much benefit. However, in the case of multiple nesting of complex judgments, using return can significantly improve the readability of the code.

In addition, when you need to use else, you can also do this:

protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.txt);
    if (getArticle().getComment() == null) {
    
    
      //把else里的语句 放到里面 最后加上return 跳过后面语句
      textView.setText("暂时没有评论");
      return;
    }
    String commentContent = getArticle().getComment().getContent();
    textView.setText(commentContent);

4 Summary

The main thing is to clarify the parameters received by the method you wrote or the type of data received by the Api, and what are the possibilities. Then just prescribe the right medicine and write a judgment~~

Guess you like

Origin blog.csdn.net/aa35434/article/details/129116456