Have you abused the time limit?

Guide As a brick-moving party, we must be familiar with short-term, so why don't I suggest you use "! = Null" as a short-term?

Have you abused the time limit?  Have you abused the time limit?

problem

In order 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 null code in the project, how ugly and cumbersome! How to avoid this situation? Have we abused null?

Essence answer

This is a problem often encountered by beginner and intermediate programmers. They always like to return null in methods, so when calling these methods, they also have to judge null.

In addition, perhaps affected by this habit, they always subconsciously believe that all returns are untrustworthy. In order to protect their own procedures, they have added a lot of empty space.

After voicing, return to the subject itself and make an unprecedented judgment. Please distinguish the following two situations:

  • null is a valid and meaningful return value. (Where null is a valid response in terms of the contract; and)
  • 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 look down, and then we will discuss these two situations in detail.

① Let me talk about the second situation first

Null is an unreasonable parameter, so the program should be explicitly interrupted and errors will be thrown out. This situation is common in 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 it will not work.

You have to perceive this situation and tell the caller "Hey, buddy, you pass a null to me."

Compared with empty sentences, there are two better ways to check:

  • In the assert statement, you can put the cause of the error in the argument of the assert. This will not only protect your program from going down, but also return the cause of the error to the caller. Wouldn’t it be a two-shot. (The original text introduces the use of assert, omitted here)
  • You can also throw a null pointer exception directly. As mentioned above, null is an unreasonable parameter at this time. If there is a problem, there is a problem, and it should be thrown out generously.

②The first situation will be more complicated

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

Here are some practical suggestions

① If the return type of the method is collections.

When the returned result is empty, you can return an empty collection(empty list) instead of returning null.

In this way, the calling side can boldly handle this return. For example, after the calling side gets the return, it can print list.size() directly without worrying about the null pointer problem.

What? When I want to call this method, I don’t remember whether the method was implemented in accordance with this principle before? So, code habits are very important!

If you develop the habit of writing code like this (returning empty collections instead of returning null), you can boldly ignore the null judgment when you call the method you wrote.

②The return type is not collections, what should I do?

Then return an empty object (not a null object), the following is 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 corresponding actions based on user input.

If the user 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.

Let's remake

The class definition is as follows, so that after defining the findAction method, make sure that no matter what the user inputs, no null object will be returned:

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:

① Redundancy: every time an object is acquired, it is judged as 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();} 

②Streamline

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

Because no matter what the situation, it will not return an empty object, so after getting the action through findAction, you can safely call the action method.

Other selected answers

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

For example, use:

"bar".equals(foo) 

Instead of:

foo.equals("bar") 

② In Java8 or guava lib, the Optional class is provided, which is an element container, through which objects can be encapsulated, which can reduce null judgment. But the amount of code is still a lot. accurate.

③If you want to return null, please stop and think about whether this place should throw an exception. Linux should be learned like this

Guess you like

Origin blog.csdn.net/Linuxprobe18/article/details/113103336