Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the problems with Null?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the problems of Null". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. The problem of Null

Suppose you now have a method that requires three parameters. The first parameter is required, and the last two parameters are optional.

In the first case, when we call this method, we can only pass in two parameters, and for the third parameter, we don't have it in the context, so when we call the method, we need to tell the method with a special value:

We can't get the third parameter, and the parameter doesn't exist or is not clear.

What should be used for this particular value? In Java, we will choose to use null to express this situation.

In the second case, if we have three parameters when calling the method, but the third parameter has no value, we also need to pass in a special value to indicate:

Parameter exists, but has no value.

What is this special value? Yes, in Java, it's null again.

As you can see, now the meaning of the null value itself has two meanings:

Parameter does not exist

Parameter has no value

Ambiguity can be avoided as much as possible in computer science. Therefore, the ambiguity of null values is a design flaw in Java. However, not only in the Java language, however, null ambiguity is a widespread problem in programming languages. This problem is called the Null reference problem.

Null citation is a long and notorious problem in computer science. In 1964, it was invented by Tony Hall, the creator of the fast scheduling algorithm. He claimed it was a billion-dollar mistake.

In Java, when we call a method or property with an object value of null, we report java.lang.NullPointerException, or NPE for short.

Traditionally, these NPE problems have to rely entirely on the careful inspection of programmers themselves. Null checks are filled between the lines of Java code, making the code bloated and ugly and disgusting.

At the same time, due to the ambiguity of NPE, developers are often unable to completely protect NPE, which makes NPE a nightmare for developers. Logically, an object exists, but it does not know its clear meaning, but as long as it refers to the method of an object that does not have a clear meaning, it will be told NPE, which is simply impossible to guard against.

And, to make matters worse, in Java, NPE is a run-time exception, which means that NPE cannot detect it early, and problems can only occur when it is online.

Pesky null, the huge cost of NPE, so that Java developers continue to practice, using a variety of methods to deal with null, let's take a look at these methods.

NPE is a run-time exception that can only be caused while the system is running, so the code review cannot find it in advance. If we can find a way to detect the NPE that occurs at run time in advance when compiling the code, then we will greatly reduce the damage caused by NPE to the system.

As a result, the @ NonNull annotation came out of nowhere.

two。 Notes that came out of nowhere.

The @ NonNull annotation is a tag that can be associated with IDE: IDE marks a warning when a NPE may occur.

Let's look at a piece of code first:

The above code does not add @ NonNull, and you can see that IDE does not give any warning.

Let's add the @ NonNull annotation to see:

As you can see, the Idea and @ NonNull annotations are linked and give a warning of a possible NPE.

With this warning, it is not enough for a complex project, because these warnings can easily be ignored, and even if ignored, the project can still be compiled and run.

So, can we add another step of inspection? When a suspicious NPE is detected, compilation is not allowed at all. It's time to introduce findbugs to you!

3. Findbugs came out.

Let's first configure findbugs in maven:

4.0.0 com.github leetcodeMaster 1.0-SNAPSHOT src/main/resources true * * / * .xml * * / .properties src/main / java * * / * .xml * * / .properties org.apache.maven.plugins maven-compiler-plugin 8 8 org.codehaus.mojo findbugs-maven-plugin 3.0.5 Low Medium true True conf/findbugs-include-filter.xml run-findbugs compile Check com.google.guava guava 19.0 org.apache.commons commons -lang3 3.3.2 com.google.code.findbugs jsr305 3.0.2

Then run maven to compile the project.

Mvn clean compile findbugs:findbugs

As you can see, findbugs found that the project build process was interrupted by the possible occurrence of NPE at run time.

Let's open the findbugs interface to see the specific location of the error report:

You see, findbugs has accurately identified the source of possible NPE.

Through the above means, we try our best to advance the NPE to the compilation time.

But, ah, for a large and complex project, it is not enough to use static code checking. Because of static code checking tools like findbugs, it is not possible to check every NPE checkpoint in place. In addition, detection problems sometimes relax inspection requirements for business reasons.

Don't panic, we can combine static code review with some other methods to block the NPE problem, which is what we're going to talk about Optional.

4. Using Optional to remove ambiguity

Java programmers complain because of the overwhelming number of null checks. So since Java8, with reference to google's guava, the Optional type has been introduced to avoid every tedious and ugly null check.

Optional is essentially a container that holds a value of variable type T. Therefore, there are only two cases in which the value in the container Optional is either a variable value of type T or null.

For possible cases of null, Optional itself provides corresponding methods for users to call from creation, inspection, extraction, and use. And adopt a very clear meaning method to eliminate the ambiguity of null.

Let's look at the sample code:

Class Player {private int id; private String name; public int getId () {return id;} public void setId (int id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name } public class Optional4NPE {public static void main (String [] args) {Optional optionalPlayer = Optional.ofNullable (null); optionalPlayer.ifPresent (u-> System.out.println (u.getName ();}}

The above code uses an ofNullable in Optional to create an Optional container with a type of Player and a value of null.

Running result:

'Process finished with exit code 0'

After running, the code has no output and no NPE exception. The reason there is no output is that we passed in a null value, which null indicates that the value does not exist. At this point, we call the ifPresent method of Optional to determine that the printout will be performed only if there is a value.

Next, let's replace null with a meaningful value.

Import java.util.Optional;class Player {private int id; private String name; public int getId () {return id;} public void setId (int id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name }} public class Optional4NPE {public static void main (String [] args) {Player player = new Player (); player.setId (1); player.setName ("demoUser"); Optional optionalPlayer = Optional.ofNullable (player); optionalPlayer.ifPresent (u-> System.out.println (u.getName ());}}

Output result:

DemoUserProcess finished with exit code

As you can see, the printout method is executed when a player that we created is passed in.

As we have found above, through the ifPresent method of Optional, we make clear the meaning of null and make it clear that as long as the value is null, it means that it does not exist. What if a variable exists but has no value or no meaningful value?

Let's change the code:

Import java.util.Optional;class Player {private int id; private String name; public int getId () {return id;} public void setId (int id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name }} public class Optional4NPE {public static void main (String [] args) {Player player = null; Player defaultPlayer = new Player (); defaultPlayer.setId (1); defaultPlayer.setName ("- undefinedNAME-"); Player player1 = Optional.ofNullable (player) .orElse (defaultPlayer); System.out.println (player1.getName ());}}

The running results are as follows:

-undefinedNAME-Process finished with exit code 0

You can see here that we use the orElse method to return a default value when a variable has a value of null. By returning the default value, we make it clear that another meaning of null is that the object exists, but it may not make any practical sense.

The emergence of Optional greatly improves the quality of our Java code, reduces the possibility of NPE, and greatly enhances the readability of the code.

By using Optional, developers can also use the Null Object Pattern pattern to deal with Null problems very naturally and easily. Optional is well worth using in a wide range of projects.

This is the end of the content of "what are the problems with Null"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report