Commonly, there is no reason to return null from an array or collection returned method which would require extra null check instead of returning empty array or collections.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Cheese[] getCheeses(){ | |
if (chesesInStock.size() == 0){ | |
return null; | |
} | |
} | |
//REQUIRES EXTRA NULL CHECK | |
public void test(){ | |
Cheese[] cheeses = shop.getCheeses(); | |
if (cheeses != null && | |
Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON)) | |
System.out.println("Jolly good, just the thing."); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private final static Cheese[] NULL_CHEESE_ARRAY = new Cheese[0]; | |
public Cheese[] getCheeses(){ | |
if (chesesInStock.size() == 0){ | |
return NULL_CHEESE_ARRAY; | |
} | |
} | |
//NO NEED NULL CHECK | |
public void test(){ | |
Cheese[] cheeses = shop.getCheeses(); | |
if (Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON)) | |
System.out.println("Jolly good, just the thing."); | |
} |
No comments:
Post a Comment