One thing to avoid when using Objects. requireNonNull in Java 8

Consider the following singleton:

public enum MyVeryImportantSingleton {
  INSTANCE;

  private String a;
  private String b;

  public void set(String a, String b) {
    this.a = Objects.requireNonNull(a);
    this.b = Objects.requireNonNull(b);
  }
}

If it would be called in the following manner:

try {
  MyVeryImportantSingleton.INSTANCE
    .set("Hello world", null);
}
catch (Throwable t) {
  ...all sorts of recovery operations
  ...leaving the system running
}

MyVeryImportantSingleton‘s a-field is set, but the b-field is left in its previous state. This, of course, could turn into really bad news.

The right way to implement set() would be:

public void set(String a, String b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
this.a = a;
this.b = b;
}

This is also a great praxis for all form of input error checking. It should first be finished, and then the object state can be updated once all input is ok.

You never know when your method will be called from inside a catch-block by a programmer that, incorrectly assumes the object state is okay even if an exception was thrown.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.