How to avoid !=null statement in Java?

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

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.

New Vulnerability to be Found in Google+

Due to this vulnerability it was possible to obtain private information of 52.5 million accounts
11 December 2018   108

Google decided to close the social network Google+ not in August 2019, but in April. The reason was another vulnerability in the API, due to which it was possible to obtain private information of 52.5 million accounts. The company plans to close the social network API until mid-March 2019.

By December 10, 2018, the following error information was published:

  • Third-party applications requesting access to profile data, because of the bug in the API, received permission to view information, even if it is hidden by privacy settings;
  • the names of users, their email addresses, information about occupation, age and other confidential information were at risk;
  • passwords, financial data and national identification numbers have not been compromised;
  • the company has no evidence that anyone has exploited the vulnerability;
  • the error was fixed within 6 days: from November 7 to November 13, 2018.
  • Google said it sends notifications to all users affected by the bug.

The previous data leak of Google+ users occurred in October 2018. Then about 500 thousand accounts were compromised. The attackers could get the names, email addresses, age, gender and occupation of users.