Programmers, if the system suddenly reports a null pointer exception, you must feel as embarrassed as if you swallowed a fly.
So how do you reduce NPE in your daily development process?
The problem | answer |
---|---|
The status quo | A large number of null pointer exceptions occur when a null value is returned |
purpose | Improved method return value to reduce the occurrence of null pointer exceptions |
Realize the path | Method returns an empty collection or an empty array |
Come with me!
background
The following method seems common.
private final List<Chesse> chessesInStock= ...
public List<Cheese> getCheeses(a){
return cheesesInStock.isEmpty()?null:new ArrayList<>(cheesesInStock);
}
Copy the code
If you go to buy cheese and there is no cheese available, there seems no reason to point out this scenario.
But if you do, the client needs to add extra code to handle the possibility of returning a null value. Example code is as follows:
List<Cheese> cheeses = shop.getCheeses();
if(cheses ! =null && cheeses.contains(Cheese.STILTON)){
System.out.println("jolly good");
}
Copy the code
Every method that returns a null value uses the above treatment and should be replaced with an empty collection or array.
This is a bad trend because programmers on the client side may forget to write special code to handle null values returned.
This error can last a long time because such methods usually return one or more objects.
Does not return an empty collection an empty array argument
Returning an empty value instead of an empty container also complicates the implementation of the method.
A common argument is that returning an empty value is better than returning an empty collection because of the performance cost of creating an empty container.
This argument is wrong for two reasons:
First, there is no need to worry about performance unless there is evidence that creating an empty container hurts performance;
Two, you can return an empty collection or array without creating them.
Return empty collection
The following is a typical code that returns a possible empty set, and in general, that’s all you need.
public List<Cheese> getCheeses(a){
return new ArrayList<>(cheeseInStock);
}
Copy the code
There is no proof that creating an empty collection hurts performance, and you can avoid creating an empty collection by returning the same immutable empty collection. Since immutable objects can be freely shared, here’s how to use them.
Demand scenarios | code |
---|---|
An empty List | Collections.emptyList() |
An empty Set | Collections.emptySet() |
An empty Map | Collections.emptyMap() |
Keep in mind, however, that these actions are just optimizations and are rarely called, so if you think you need them, compare performance before and after the call to make sure it really works.
public List<Cheese> getCheeses(a){
returncheesesInStock.isEmpty()? Collections.emptyList():new ArrayList<>(cheesesInStock);
}
Copy the code
Return an empty array
The scenario with arrays is the same as with collections, never return null values, instead return an array of bit zero length. Often, you should simply return an array of the appropriate length, perhaps zero length.
Note that we pass an array of length 0 into the toArray method to represent the expected return type;
public Cheese[] getCheeses(){
return cheesesInStock.toArray(new Cheese[0]);
}
Copy the code
If you think that creating an array of length 0 would degrade performance, you can return the same array of length 0, because all arrays of length 0 are immutable;
private static final Cheese[] EMPTY_ARRAY= new Cheese[0];
public Cheeses[] getCheeses(){
return cheesesInStock.toArray(EMPTY_ARRAY);
}
Copy the code
In the optimized version, we pass the same empty array to every toArray call, which will be returned from getCheeses, whether cheesesInStock is empty or not. Don’t expect pre-allocated arrays to improve performance, research shows it’s counterproductive.
return cheesesInStock.toArray(new Cheese[cheesesInStock.size()]);
Copy the code
summary
If you can only remember one sentence: return an empty collection or array instead of a null value.
Returning null makes your API harder to use and more error-prone, with no performance advantage;
Original is not easy, attention is precious, forwarding price is higher! Reprint please indicate the source, let us exchange, common progress, welcome communication.