Remove annoying "! = Null" (empty sentence statement)

Remove annoying "! = Null" (empty sentence statement)
Transfer: https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/avoiding-null-statements-in-java.md

To avoid a null pointer calls, we often see such a sentence

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

Ultimately, the project there will be a lot of empty sentenced code, how to avoid this? Do we judge abused empty it?


To myself - were sentenced unprecedented, please distinguish between the following two situations:

null is a valid meaningful return value (the Where IS A null in the Response! Valid at The Terms of Contract; and)
null null is incorrect (Where it is not a valid response .)
You may not understand these two words meaning, do not worry, read on, the next will be discussed in detail in both cases


Case 1 null is a reasonable argument, it should be clear interrupt routine, throwing out the error.

This situation is common in api method. For example, you develop an interface, id is a required parameter, if the caller did not pass this parameter to you, of course not. When faced with this situation, tell the caller, "Hey, buddy, you pass a null Zuoshen to me."

With respect to the sentence null statement, a better way of checking two

  • assert statement, you can put into the cause of the error in the parameters assert, not only to protect your program does not go down, but also the cause of the error is returned to the caller, it would serve two purposes. (Text describes the use assert omitted here)
  • It can also be directly throw a null pointer exception. Above that, then null is a reasonable argument, there is a problem is a problem, it should throw out openly.

The second case is more complicated. In this case, null is a "look" reasonable value, for example, I query the database, a query under the condition that there is no corresponding value at this time considered null express the concept of "empty".

Give some advice here

  • If the return type of the method is Collections, when the result is empty, you can return an empty collections (empty list), rather than return null. Such side can call the bold processing returns, e.g. calling side returns to get , you can directly print list.size (), and do not need to worry about the null pointer issues. (What? Think this method is called, can not remember before implementing this method has not in accordance with this principle? So, the code is very important habit! Habit if you are writing code like this (to return empty collections rather than return null), when you call a method to write their own, we can boldly ignored sentenced empty)
  • Return type is not collections, and how to do it? Then returns a null object (not null object), give the following "chestnut", assume that the following code
public interface Action {
  void doSomething();}

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

Which, Parse has an interface FindAction, this interface will be based on user input, to find and execute the corresponding action. If the user does not input, you may not find the corresponding operation (the Action), thus findAction will return null, the next time the method doSomething action call, will be a null pointer. One way to solve this problem is to use Null Object pattern (Null Object mode)

Let's transform the look

Class is defined as follows, after this definition findAction method to ensure that no matter what the user input, 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;
    }
  }}

The following two examples contrast calling

  1. Redundancy: Each get an object, it is judged once 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();}
  1. streamline
ParserFactory.getParser().findAction(someInput).doSomething();

Because no matter what happens, will not return empty object, so by the findAction get action, action way to call safely.

Other answers selection:

  • If you want equal method, using object <unlikely empty> .equal (object <possibly empty>)) For example: the use of "bar" .equals (foo) instead foo.equals ( "bar")
  • Java8 or guava lib, there is provided Optional class, which is a container element, which is encapsulated by the object, the empty judgment can be reduced. However, the amount of code or less. accurate.
  • 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/qq_35548458/article/details/93379726