This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Avoiding NullPointerException in Java?

I use a lot to avoid NPE. object ! = null

What is substitution:

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

Answer:

To me, this sounds like a fairly common problem that developers from junior to mid-level tend to face at some point: they either don’t know or don’t trust the contract they’re working on, and overcheck on defense to be ineffective. In addition, when writing their own code, they tend to rely on returning empty code to indicate something that requires the caller to check for invalidity.

In other words, there are two situations where invalid checks can occur:

If invalidity in the contract is valid reply: and

If it’s not a valid response.

(2) Easy. Either use statements (assertions) or allow failure (for example, empty point detracting). Assertions are a highly unused Java feature that was added in 1.4. The syntax is: assert

Assert <condition> or assert <condition> : <object>Copy the code

Where a Boolean expression is, is an object whose method output will be included in the error. toString()

If the case is incorrect, the declaration throws (). By default, Java ignores assertions. You can enable assertions by passing the option to the joint venture. You can enable and disable assertions for individual classes and packages. This means that you can validate code with assertions during development and testing, and disable them in production, although my tests show little performance impact of assertions. assertErrorAssertionError-ea

It’s ok not to use assertions in this case because the code will fail, which is what happens if you use assertions. The only difference is that, with assertions, it might happen faster, in a more meaningful way, and possibly with additional information, which might help you figure out why it’s happening if you’re not expecting it.

(1) It’s a little difficult. If you have no control over the code you call, it will get stuck. If invalid is a valid response, you must check.

However, if it’s code you control (which is usually the case), it’s a different story. Avoid using null as a response. Using the method of returning collections, it’s easy: return an empty collection (or array) instead of an empty collection almost all the time.

For non-collectors, it can be more difficult. Take this as an example: If you have the following interface:

public interface Action {
  void doSomething();
}

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

Parser needs the original user to input and find something to do, perhaps if you’re executing a command line interface for something. Now, without proper action, you may have the contract return invalid. This leads to the empty check you are talking about.

Another solution is to never return null and instead use the empty object pattern:

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; }}}Copy the code

Comparison:

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();
}
Copy the code

ParserFactory.getParser().findAction(someInput).doSomething();
Copy the code

This is a better design because it leads to cleaner code.

That being said, perhaps the findAction () method is entirely appropriate when publishing exceptions with meaningful error messages, especially if you rely on user input. It is much better to throw an exception for the lookup method than to call the method with a simple empty exception that explodes without explanation.

try { ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); } or, if you think the try/capture mechanism is too ugly, rather than doing nothing, your default action should provide feedback to the user. public Action findAction(final String userInput) { /* Code to return requested Action if found */ return new Action() { public void doSomething() { userConsole.err("Action not found: " + userInput); }}}Copy the code

The article translated from stackoverflow.com/questions/2…

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️