How to avoid !=null statement in Java?

Resolve methods with code examples for popular Java issue
14 August 2017   2147

Hype.Codes continues to find solutions to the most popular programming issues.

We've made a research and found out that =null! statement can appear in two situations, and every situation has its resolve methods..

  1. A valid response in terms of the contract;
  2. It isn't a valid response.

Let's check the first situation.

Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time. 

With non-collections it might be harder. Consider this as an example: 

public interface Action {
  void doSomething();
}

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

where Parser takes raw user input data and finds something to do, perhaps if you're implementing a command line interface for something. An alternative solution is to never return null and instead use the Null 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;
    }
  }
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
}
Action action = parser.findAction(someInput);
if (action == null) {
  // do nothing
} else {
  action.doSomething();
}

to

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

which is a much easier to use.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with an error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
    ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
    userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do 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);
        }
    }
}

Now, let's solve the second situation.

Feel free to use assert statements (assertions) or allow failure (for example,NullPointerException). Assertions are a highly-underused Java feature that was added in 1.4. The syntax is:

assert <condition>

or

assert <condition> : <object>

where <condition> is a boolean expression and <object> is an object whose toString()method's output will be included in the error.

An assert statement throws an Error (AssertionError) if the condition is not true. Java ignores assertions by default. You can enable assertions by passing the option -ea to the JVM. You can enable and disable assertions for individual classes and packages. This means that you can validate code with the assertions while developing and testing, and disable them in a production environment. 

Not using assertions in this case is good because the code will just fail, which is what will happen if you use assertions. The only difference is that with assertions it might happen sooner, in a more-meaningful way and possibly with extra information, which may help you to solve the issue.

TIOBE Index June 2019 to be Rolled Out

Java is still on the top, but experts noted fast growth of Python search queries, and they believe it can reach 1st place in 3-4 years
13 June 2019   214

June 2019 TIOBE Index has been released. Analysts noted a sharp increase in the proportion of searches for Python.

This month Python has reached again an all time high in TIOBE index of 8.5%. If Python can keep this pace, it will probably replace C and Java in 3 to 4 years time, thus becoming the most popular programming language of the world. The main reason for this is that software engineering is booming. It attracts lots of newcomers to the field. Java's way of programming is too verbose for beginners. In order to fully understand and run a simple program such as "hello world" in Java you need to have knowledge of classes, static methods and packages. In C this is a bit easier, but then you will be hit in the face with explicit memory management. In Python this is just a one-liner. 
 

TIOBE Team

Experts attributed the growing popularity of Python to the fact that now many have hit the development of software. And newcomers prefer Python - succinct and concise. According to analysts, Java for beginners is too verbose, and C sooner or later will force to understand the intricacies of memory management.