StackOverflow Tour <1>------{get rid of annoying '!=null ' judgment}

Source: Internet
Author: User

Problem

To avoid null pointer calls, we often see a statement like this

NULL) {    someobject. Docalc ();}

Eventually, there will be a lot of empty code in the project, how ugly and cumbersome! How to avoid this situation? Are we abusing the sentence?

Reply

This is an early, intermediate program ape often encounter problems. They always like to return Null in the method, so when these methods are called, they also have to be sentenced to empty. In addition, perhaps affected by this habit, they always subconsciously believe that all returns are not trustworthy, in order to protect their own procedures, a large number of empty sentences.

After the completion of the groove, back to the topic itself, the award of unprecedented, please distinguish 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 (Where it isn ' t a valid response.)

You may not understand the meaning of these two words, do not worry, continue to look down, the following will be discussed in detail in these two situations

Let's start with the 2nd situation.

Null is an unreasonable parameter, you should explicitly interrupt the program and throw out the error. This situation is common in API methods. For example you have developed an interface, ID is a required parameter, if the caller does not pass this parameter to you, of course not. You have to be aware of the situation and tell the caller, "Hey, man, you sent me a null."

There are two better ways to check than to empty a sentence.

    1. Assert statement, you can put the wrong reason in the assert parameter, so that not only can protect your program not go down, but also can return the wrong reason to the caller, it is not double benefit. (The original text describes the use of Assert, omitted here)
    2. You can also throw a null pointer exception directly. Above said, at this time null is an unreasonable parameter, there is a problem is that there is a problem, it should be openly thrown out.
The 1th situation is more complicated.

In this case, NULL is a "seemingly" reasonable value, for example, I query the database, a query condition, there is no corresponding value, when NULL is expressed as "empty" concept.

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 collections (empty list) without returning NULL. This return can be handled boldly by the calling side, such as when the call side gets returned and can print directly List.size () without having to worry about null pointer problems. What If you want to call this method, do not remember to implement this method before the principle? So, code habits are important! If you get into the habit of writing code like this (returning an empty collections without returning null), you can boldly ignore the empty sentence when you call your own method of writing)
    • return type is not collections, what do you do? Then return an empty object (not a null object), and here is a "chestnut", assuming the following code
Action {  dosomething ();} findaction (userinput);}  

Where parse has an interface findaction, this interface will find and execute the corresponding action according to the user's input. If the user input is not correct, the corresponding action (action) may not be found, so findaction will return null, and then when Action calls the DoSomething method, a null pointer appears. One way to solve this problem is to use the null object pattern (empty objects mode)

Let's change it.

The class is defined as follows, so that when the Findaction method is defined, the null object is not returned, regardless of what the user enters, public class Myparser implements Parser {private static Action Do_ nothing = The 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 copies of call instance 1. Redundancy: Each time an object is fetched, the empty

Parserfactory. Getparser ();  This would is an example of where null isn ' t (or shouldn ' t is) a valid response}= Parser. Findaction (Someinput) ; //Do nothing} else {action. dosomething ();}     
    1. Streamline
Parserfactory. Getparser (). Findaction (Someinput). dosomething ();  

Because no empty object is returned in any case, you can safely invoke the action's method after you get the action through findaction.

Other answers featured:
    • If you want to use the equal method, use object< cannot be empty >.equal (object< may be empty >)) For example: Use "Bar". Equals (foo) instead of Foo.equals ("bar")
    • Java8 or Guava Lib, which provides the optional class, which is an element container through which to encapsulate objects, you can reduce the space penalty. But the amount of code is still quite a bit. Upset.
    • If you want to return null, make sure to think about whether this place should throw an exception

StackOverflow Link: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab= Votes#tab-top

Reprinted from: https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/avoiding-null-statements-in-java.md# problem

StackOverflow Tour <1>------{get rid of annoying '!=null ' judgment}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.