How to avoid !=null statement in Java?

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

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.

What is Web3j?

Small review of lightweight Java and Android library for integration with Ethereum clients
15 December 2017   816

What is webj3?

web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with clients (nodes) on the Ethereum network:

web3j architecture
Web3j Architecture

This allows you to work with the Ethereum blockchain, without the additional overhead of having to write your own integration code for the platform.

According to the developers, these are the features:

  • Complete implementation of Ethereum's JSON-RPC client API over HTTP and IPC
  • Ethereum wallet support
  • Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart contracts from native Java code (Solidity and Truffle definition formats supported)
  • Reactive-functional API for working with filters
  • Ethereum Name Service (ENS) support
  • Support for Parity's Personal, and Geth's Personal client APIs
  • Support for Infura, so you don't have to run an Ethereum client yourself
  • Comprehensive integration tests demonstrating a number of the above scenarios
  • Command line tools
  • Android compatible
  • Support for JP Morgan's Quorum via web3j-quorum

It has five runtime dependencies:

  • RxJava for its reactive-functional API
  • OKHttp for HTTP connections
  • Jackson Core for fast JSON serialisation/deserialisation
  • Bouncy Castle (Spongy Castle on Android) for crypto
  • Jnr-unixsocket for *nix IPC (not available on Android)

It also uses JavaPoet for generating smart contract wrappers.

Lear more at GitHub.