Java: a fast / elegant way to check for null

In the program that I am writing now, I find that I am doing the following a lot ...

Map<String,List<String>> network = loadSerializedObj(file); // null if failed if(network != null) { anonNet = util.anonymize(newNet); } else { // Some sort of error handling. System.out.println("Some sort of error message. Exiting..."); System.exit(0); } 

Is there a shorter way to handle the event when loading a serialized object from a file does not work and the method returns null? Any advice is generally welcome. Anywhere I can make it more elegant?

+4
source share
7 answers

you should make loadSerializedObj throw an exception instead of returning null. you can return null when you have nothing to return. when something breaks, you should throw an exception.

+6
source

In this case, you can use the catch exception.

 Map<String,List<String>> network = loadSerializedObj(file); // null if failed try { anonNet = util.anonymize(newNet); } catch(NullPointerException npe) { System.out.println("Some sort of error message. Exiting..."); System.exit(0); } 

but you must specify util.anonymize to throw a NullPointerException if it hasn't already.

+2
source

you may have some

 class MyAssert { static<T> assertNotNull(T object) { if (object == null) { System.out.println("something is wrong..."); System.exit(0); } return object; } } 
+1
source

Try returning an empty card instead of a null value:

  if(!loadSerializedObj(file).isEmpty()) { anonNet = util.anonymize(newNet); } else { // error handling } private Map<String,List<String>> loadSerializedObj(File file) { // do stuff if(mapObject == null) { mapObject = Collections.emptyMap(); } return mapObject } 
+1
source

You can do a static import of a function called n (object) that returns boolean if null. Or use Groovy :)

0
source

I think you have as good as saving easy to read / maintain code.

0
source

Guava preconditions can be a good way to perform concise readable checks.

 Preconditions.checkNotNull(myReference, "My error message"); 
0
source

Source: https://habr.com/ru/post/1346155/


All Articles