The problem

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

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

You end up with a lot of null-detection code in your project, which is ugly and cumbersome! How can this be avoided? Have we abused short calls?

The essence to answer

This is a common problem for early and intermediate programmers. They always like to return null in their methods, so they have to nullify those methods when they are called. In addition, perhaps influenced by this habit, they subconsciously believe that all returns are untrustworthy and add a lot of nullates to protect their program.

Back to the topic itself:

For judgment, please distinguish between the following two situations:

Where null is a valid response in terms of the contract; and)

Where it isn’t a valid response.

If you don’t know what these two sentences mean, don’t worry, read on and we’ll discuss both cases in detail

Let’s start with case number two

Null is an unreasonable argument and should explicitly interrupt the program and throw out errors. This is often the case with API methods. For example, if you develop an interface, id is a mandatory parameter, if the caller does not pass this parameter to you, of course not. You have to sense this and tell the caller “Hey, dude, what are you doing passing null to me?”

There are two better ways to check for null statements

You can use the assert argument to protect your program from the error and to return the error reason to the caller. (This article describes the use of assert. It is omitted here.)

(2) You can also throw a null pointer exception directly. In this case, null is an invalid parameter. If there is a problem, it should be thrown out.

Case 1 is a little more complicated

In this case, null is a “seemingly” reasonable value. For example, if I am querying a database and there is no value for a particular query, null is the definition of null.

Here are some practical tips:

1. If the return type of the method is collections, you can return an empty collections (empty list) instead of null, so that the calling side can handle the return boldly. For example, when the calling side gets the return, Print list.size() without worrying about null Pointers. (what? When you want to call this method, do you remember that the method was implemented in accordance with this principle? So code habits matter! If you get into the habit of writing code like this (returning null collections instead of null), you can boldly ignore nulls when calling your own methods.

2. What if the return type is not Collections?

Return an empty object (instead of a null object), for example, assuming the following code

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

Parse has an interface, FindAction, that finds and executes actions based on user input. If the user typed something wrong, the Action might not be found, so findAction returns null, and then when the Action calls the doSomething method, the null pointer will appear.

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

Let’s reinvent it

The class definition is as follows, so that when you define the findAction method, you make sure that no matter what the user enters, it doesn’t return a null object. Okay

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; }}}Copy the code

Compare the two invocation examples below

1. Redundancy: Every time an object is acquired, null is judged

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(); }Copy the code

2, compact

ParserFactory.getParser().findAction(someInput).doSomething();
Copy the code

Because no empty object is returned in any case, you can safely call the action’s methods once you get the action in findAction.

Other selected answers:

1. If you want to use the equal method, use the object< impossible empty >.

For example, use:

"bar".equals(foo)
Copy the code

Rather than

foo.equals("bar")
Copy the code

Java8 or Guava Lib provides the Optional class, which is an element container that encapsulates objects to reduce nulls. But it’s still a lot of code. Not great.

3. If you want to return NULL, stop and think about whether this is a better place to throw an exception

The last

Thank you for reading here, the article is inadequate, welcome to point out; If you think it’s good, give me a thumbs up.

Also welcome to pay attention to my public number: programmer Maidong, Maidong will share Java related technical articles or industry information every day, welcome to pay attention to and forward the article!