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.
One thought on “One thing to avoid when using Objects. requireNonNull in Java 8”