How to avoid !=null statement in Java?

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

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.

Canonical to Represent Minimal Ubuntu

New version of Ubuntu is created for servers, isolated containers based on Docker and cloud systems
12 July 2018   105

Ubuntu team presented a simplified version of the base image - Minimal Ubuntu. It is designed for servers, isolated containers based on Docker and cloud systems. The release features high performance, minimal load time and automation of applications in the cloud.

The small footprint of Minimal Ubuntu, when deployed with fast VM provisioning from GCE, helps deliver drastically improved boot times, making them a great choice for developers looking to build their applications on Google Cloud Platform.
 

Paul Nash

Group Product Manager, Google Cloud

The authors of the project emphasize the size of the distribution kit, which "weighs" 157 MB, and also supports the main cloud systems like Amazon EC2, Google Compute Engine (GCE), LXD and KVM / OpenStack, each of which has its own optimized version of the package. In addition, the OS-based image for operating with containers based on the Docker platform, compatible with the Kubernetes.

Minimal Ubuntu is designed for automated execution, so it includes only a minimal set of tools. The distribution can be upgraded to a set of Ubuntu Server packages using the special utility "unminimize", which returns components that are convenient for interactive management.

According to Canonical representatives, the deletion of the manual control functions resulted in the acceleration of the load time by 40% and the reduction of the occupied disk space by 50%. At the same time, this release remained completely compatible with all the packages from standard Ubuntu repositories. Required packages can be installed using the standard package manager apt or using snapd, which are included in the distribution by default.

Two assemblies are available for download, based on Ubuntu 16.04 LTS and 18.04 LTS. You can download them on the official website.