[Stackoverflow good question] Remove annoying "! = Null & quot; (empty statement), stackoverflownull

Source: Internet
Author: User

[Stackoverflow good question] Remove annoying "! = Null "(empty statement), stackoverflownull
ProblemTo avoid NULL pointer calls, we often see such statements

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

In the end, there will be a lot of empty code in the project. How ugly and tedious it is! How can this problem be avoided? Have we abused the sentence?
Excellent answer:This is a common problem for beginners and intermediate programmers. They always like to return null in the method. Therefore, they have to judge null when calling these methods. In addition, they may be influenced by this habit. They subconsciously think that all responses are untrusted. To protect their own programs, a lot of questions are added. After the discussion is completed, return to the question 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 is invalid or incorrect (Where it isn't a valid response .) you may not understand the meaning of these two sentences. If you are not in a hurry, go on and discuss the two situations in detail.
2nd cases firstNull is an unreasonable parameter. It is necessary to explicitly interrupt the program and throw an error. This situation is common in api methods. For example, if you have developed an interface, id is a required parameter. If the caller does not pass this parameter to you, of course not. You need to perceive this situation and tell the caller, "Hey, buddy, what do you want to do if you pass null ". Compared with the empty statement, there are two (1) assert statements for better check. You can put the cause of the error into the assert parameter, which not only protects your program from going down, in addition, it is not necessary to return the cause of the error to the caller. (The original article introduces the use of assert, Which is omitted here) (2) You can also directly throw a null pointer exception. As mentioned above, null is an unreasonable parameter at this time. If there is a problem, it should be left aside.
The 1st cases are 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, null indicates the concept of "null. Here are some practical suggestions: 1. If the return type of the method is collections, you can return an empty collections if the returned result is null.(Empty list), instead of returning null, the call side can handle this return boldly. For example, after obtaining the return from the call side, you can print the list directly. size () does not need to worry about null pointers. (What? When I want to call this method, I do not remember whether the method was implemented in accordance with this principle? Therefore, code habits are very important! If you get used to writing code like this (returning empty collections without returning null), you can boldly ignore empty criteria when calling your own method) 2. What should I do if the return type is not collections? Return an empty object instead of a null object)For example, the following code is used:
public interface Action {  void doSomething();}public interface Parser {  Action findAction(String userInput);}

In this example, Parse has an interface FindAction, which finds and executes the corresponding action based on the user input. If the user input is incorrect, the corresponding Action may not be found. Therefore, findAction returns null. When the action calls the doSomething method, a null pointer will appear. One way to solve this problem is to use Null Object pattern (Null Object mode)
Let's modify the class definition as follows. After findAction is defined, make sure that no null object is returned no matter what the user inputs.
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: each time an object is obtained, it is null.
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. Simplified
ParserFactory.getParser().findAction(someInput).doSomething();
Because no empty object is returned in any case, you can call the action method with confidence after obtaining the action through findAction.


Other answers:1. If you want to use the equal method, use object <cannot be blank>. equal (object <may be blank>). For example: Use
"bar".equals(foo) 
Instead
foo.equals("bar") 
2. The Optional class is provided in Java 8 or guava lib. It is an element container that encapsulates objects and can reduce null determination. But there are still a lot of code. Unhappy. 3. If you want to return null, think about whether an exception should be thrown in this place.
Stackoverflow link: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java? Page = 2 & tab = votes # tab-top
Column introduction: I like stackoverflow very much and can always find a solution to the problem. The website has a popularity list. So I selected some hot questions, read all the answers to each question, and sort them out based on my own understanding. We hope that the above discussion will be presented in a more streamlined and appropriate manner. If you need to reprint, please specify the original address Http://blog.csdn.net/lizeyang
Let's take a look at this code. SystemStackOverflowException is always abnormal.

Not familiar with VB ......
But what is the role of e. Item. Checked = True? I feel a little redundant.

When you use bibernate to manage the database to query other objects, it can be executed normally. When you query "A" objects, javalangStackOverflow is generated.

Please send out the detailed error code
 

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.