当前位置:网站首页>[stack overflow problem] why don't senior programmers use "! = null" to judge null?

[stack overflow problem] why don't senior programmers use "! = null" to judge null?

2020-12-07 15:26:36 osc_ 8rbrmk98

# problem

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

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

Final , There will be a lot of empty code in the project , How ugly and tedious ! How to avoid this situation ? Are we abusing air sentences ?

# Essence answer

This is the beginning 、 The problems that middle-level programmers often encounter . They always like to return... In methods null, therefore , When these methods are called , I have to judge the void . in addition , Maybe affected by this habit , They always subconsciously think , All returns are untrustworthy , To protect your program , There's a lot of air traffic .

Make complaints about the end , Go back to the subject itself :

The verdict is unprecedented , 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 It's invalid and wrong (Where it isn't a valid response.)

You may not understand the meaning of these two sentences , Don't worry , Keep looking down , We will discuss these two situations in detail

# First of all 2 In this case

null It's just an unreasonable parameter , You should definitely interrupt the program , Throw mistakes out . This is common in api Method . For example, you developed an interface ,id Is a required parameter , If the caller doesn't pass this parameter to you , Of course not . You need to feel the situation , Tell the caller “ well , Brother , You pass on null What to do for me ".

Relative to the null statement , There are two better ways to check

(1)assert sentence , You can put the cause of the mistake in assert The parameters of the , This not only protects your program from going down , It can also return the cause of the error to the caller , Is it not to kill two birds with one stone .( The original introduces assert Use , It is omitted here )

(2) You can also throw a null pointer exception directly . It says , here null It's an unreasonable parameter , The problem is the problem , We should throw it out .

# The first 1 It's more complicated .

In this case ,null It's a ” it seems “ Reasonable value , for example , I query the database , Under a certain query condition , There is no corresponding value , here null It's an expression of “ empty ” The concept of .

# 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 going back null, In this way, the call side can boldly handle this return , For example, after the call side gets it back , Can directly print list.size(), There's no need to worry about null pointer .( what ? When you want to call this method , I don't remember whether this method was implemented according to this principle before ? So , Code habits are important ! If you form a habit , It's all written in this way ( Returns an empty collections Instead of going back null), When you call a method you write , We can boldly ignore the empty judgment )

2、 Return type is not collections, What to do ?

Then return an empty object ( Instead of null object ), The following is an example. “ chestnuts ”, Suppose you have the following code

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

among ,Parse There's an interface FindAction, This interface will be based on user input , Find and perform the corresponding action . If the user input is wrong , Maybe we can't find the corresponding action (Action), therefore findAction It will return null, Next action call doSomething When the method is used , There will be a null pointer .

One way to solve this problem , Is the use of Null Object pattern( Empty object mode )

# Let's transform

Class is defined as follows , Such definition findAction After the method , Make sure that whatever the user enters , Will not return 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 instances

1、 redundancy : Every time I get an object , Just give me a blank

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、 Streamlining

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

Because no matter what , Will not return an empty object , So by findAction Get action after , You can call action Methods .

# Other answers are selected :

1、 If you want to use equal Method , Please use object< It can't be empty >.equal(object< May is empty >))

For example, using    :

"bar".equals(foo)

instead of    

foo.equals("bar")

2、Java8 perhaps guava lib in , Provides Optional class , This is an element container , It encapsulates objects , It can reduce the number of empty sentences . But there's still a lot of code . Not great .

3、 If you want to go back null, Please stop and think about , Whether this place should throw an exception more

author :lizeyang

blog.csdn.net/lizeyang/article/details/40040817

 More highlights 
*   Google  Encouraging  13  Code review criteria , Recommended collection !
*    these SQL Incorrect usage , If you often do , It shows that your level is still very low...*    Why can't I use uuid do MySQL Primary key of ?*    Wechat page  1  Line code exposure !*    QIPA company calculates the salary according to the code line , One month Commission for employees 2.6 Million dismissed 

 Last , I recommend you an interesting and interesting official account : The guy who wrote the code , reply   interview   or   resources   Send you a complete set of Development Notes 

版权声明
本文为[osc_ 8rbrmk98]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207152119951f.html