Code quality improvement-reduce empty code

Preface

How to improve the quality of the code and make the code more robust and concise? Why is it not recommended to use != null as a null?


In order to avoid null pointer calls, we often see statements like this:

if (userId != null) {
    
    
    ... ... ...
    }

In the end, there will be a lot of null code in the project, which is ugly and cumbersome! So how do we avoid this situation? Have we abused the time limit?

This is a problem that most programmers often encounter. They always like to return null in methods, so when calling these methods, they have to be 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.

Back to the topic itself:

Before making an unprecedented judgment, please distinguish the following two situations:

1. Null is a valid and meaningful return value;
2. Null is invalid and incorrect;

If you still don’t understand the meaning of these two sentences, don’t worry, we will discuss these two situations in detail next:

The first case is more complicated, let’s talk about the second case first

Null is an unreasonable parameter, so the program should be explicitly interrupted and errors should be thrown out. This situation is common in api methods. For example, if you develop an interface, id is a required parameter. If you call the method but don't pass it to you, of course it won’t work. You have to perceive this situation and tell the caller "Hey, buddy, what are you doing by passing a null to me!?".

There are two better ways to monitor than to solve by empty sentences.

(1) In the assert statement, you can put the cause of the error in the argument of the assert, which will not only protect your program from going down, but also return the cause of the error to the caller. Wouldn’t it kill two birds with one stone (use caution in the production environment)

(2) 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.

Let's go back and talk about the first situation

In this case, null is a "seemingly" reasonable value. For example, when I check the database, under certain query conditions, the corresponding value is not queried. At this time, null can be 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 collection (empty list) instead of null, so that the caller can boldly handle the return. For example, after the caller gets the return, you can directly print list.size() without worrying about the control pin problem. (What? When calling this method, I don’t remember whether the method was implemented in accordance with this principle? So, code habit is very important! If you develop a habit, you write code like this (returning empty collections instead of returning null), you When calling a method written by yourself, you can boldly ignore the null judgment)

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 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 (empty object pattern)

Let's remake

The class definition is as follows, after defining the findAction method in this way, to ensure that no matter what the user inputs, 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 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();}
  

2. 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 references:

1. 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")
  

2. In Java 8, the Optional class is provided, which is an element container. Objects can be encapsulated through it, which can reduce null judgment.

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


Guess you like

Origin blog.csdn.net/weixin_49822811/article/details/113063036