Why is it not recommended that you use "! = null" for null?

To avoid null pointer calls, we often see statements like this

...if (someobject != null) {
    someobject.doCalc();}...

In the end, there will be a lot of empty code in the project, which is ugly and complicated. . . How to avoid this situation? Was it abused?

Many business scenarios require us to do a certain task at a specific time, and this kind of business scenario is solved by scheduled tasks. Generally speaking, the system can use message passing to replace some scheduled tasks. The two have many similarities and can replace scenarios with each other.

Essence Answers

This is a common problem encountered by beginner and intermediate programmers. They always like to return null in methods, so when calling these methods, they also have to evaluate to null. In addition, perhaps influenced by this habit, they always subconsciously believe that all returns are untrustworthy, and in order to protect their own procedures, they add a lot of nulls.

After ranting, let’s go back to the topic itself:

Before making an all-time judgment, please distinguish between the following two situations:

1. null is a valid and meaningful return value (Where null is a valid response in terms of the contract; and)

2. null is invalid and wrong (Where it isn't a valid response.)

You may not understand the meaning of these two sentences, don't worry, continue to read, the following two situations will be discussed in detail

Let's talk about the second case

null is an unreasonable parameter, so it should explicitly interrupt the program and throw an error. This situation is common with api methods. For example, if you develop an interface, id is a required parameter. If the caller does not pass this parameter to you, of course not. You need to be aware of this situation and tell the caller "Hey man, what are you doing by passing me null".

Compared with the null statement, there are two better ways to check

(1) Assert statement, you can put the cause of the error in the parameter of assert, which not only protects your program from going down, but also returns the cause of the error to the caller, which kills two birds with one stone. (The original text introduces the use of assert, which is omitted here)

(2) Null pointer exceptions can also be thrown directly. As mentioned above, null is an unreasonable parameter at this time. If there is a problem, it should be thrown out generously.

The first case is a little more complicated.

In this case, null is a "seemingly" reasonable value. For example, when I query the database, under a certain query condition, there is no corresponding value. At this time, null is regarded as expressing the concept of "empty".

Here are some practical suggestions:

1. If the return type of the method is collections, when the return result is empty, you can return an empty collections (empty list) instead of returning null, so that the calling side can boldly handle the return, for example, the calling side gets After returning, you can print list.size() directly without worrying about the null pointer problem. (What? When you want to call this method, don’t remember if you have implemented this method in accordance with this principle? So, code habits are very important! If you develop a habit, write code like this (returning empty collections instead of returning null), When you call your own method, you can boldly ignore null)

2. What if the return type is not collections?

Then return an empty object (not a null object), let's take a "chestnut", assuming the following code

public interface Action {
  void doSomething();}
 
public interface Parser {
  Action findAction(String userInput);}

Among them, Parse has an interface FindAction, which will find and execute the corresponding action according to the user's input. If the user's input is incorrect, the corresponding action (Action) may not be found, so findAction will return null, and then when the action calls the doSomething method, a null pointer will appear.

One way to solve this problem is to use the Null Object pattern

After transformation

The class is defined as follows, so that after defining the findAction method, it ensures that no matter what the user enters, it will not return a null object

public class MyParser implements Parser {
  private static Action DO_NOTHING = new Action() {
    public void doSomething() { /* do nothing */ }
  };
 
  public Action findAction(String userInput) {
    // ...
    if ( /* we can't find any actions */ ) {
      return DO_NOTHING;
    }
  }}

Compare the following two call examples

1. Redundancy: every time an object is obtained, it is judged to be empty

Parser parser = ParserFactory.getParser();
if (parser == null) {
  // now what?
  // this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
  // do nothing} else {
  action.doSomething();}

2. Simplify

ParserFactory.getParser().findAction(someInput).doSomething();

Because no empty object will be returned no matter what, so after getting the action through findAction, you can safely call the action method.

Selected other answers:

1. If you want to use the equal method, please use object<may be empty>.equal(object<may be empty>))

For example use:

"bar".equals(foo)

instead of   

foo.equals("bar")

2. In Java8 or guava lib, the Optional class is provided, which is an element container, which can be used to encapsulate objects to reduce nullability. However, there is still a lot of code. accurate.

3. If you want to return null, stop and think about whether this place should throw an exception.

From: stackoverflow

- EOF -

Like and watching is the biggest support ❤️

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326613771&siteId=291194637