Check for null in java,

if(object==null){ return; } 

the whole project consists of checking for null, is there any alternative? to make the code beautiful

  • Give more code, it’s hard to offer something better from this piece. - Ep1demic
  • Write to kotlin'e - temq

1 answer 1

The Optional class was added to Java 8 to add a new approach to handling null. Optional is some envelope over a value (functor), in which there can either be a specific value or not. For example, you can do this:

 Integer reputation = Optional.ofNullable(users.get(userId)).map(User::getReputation).orElseGet(null); 

In this case, if users.get returned null, the code in the map will not be executed. This makes it quite easy to write long pieces of code without having to think about null:

 // дурацкий пример, ничего лучше не придумал Node fifthLevelChild = Optional.of(root) // представим, что .get(0) может вернуть либо элемент, либо null, // и не стреляет исключением .map(node -> node.getChildren().get(0)) .map(node -> node.getChildren().get(0)) .map(node -> node.getChildren().get(0)) .map(node -> node.getChildren().get(0)) .map(node -> node.getChildren().get(0)) .orElseGet(null); 

If you check for null to terminate a piece of code prematurely (eg passed null -> stop work), then it is better to designate the public interface of the component that you are writing (I’m not talking about the interface as a language instruction), and check the key points to null in it so that your internal code simply cannot get null.