Good programming practices

Replace null with Null Object

December 18th, 2011

Dealing with possible null pointers often require to use “if” statement. To help programmers in those situations, I wrote a utility class which returns some default object, if null will appear. Usage is very simple – just wrap a possible null with an appropriate method from this class and you can use a variable without fear of NullPointerException. This is example of Null Object design pattern.

Three examples using NullPrevent class for replacing null with default object:

  1. public class NullPreventMain {
  2.  
  3. public static void main(String[] args) {
  4. Map<String, String> map = getMap();
  5. System.out.println("Monday: " + NullPrevent.get(map.get("Monday")));
  6. // Prints only "Friday: "
  7. System.out.println("Friday: " + NullPrevent.get(map.get("Friday")));
  8.  
  9. for (int i = 0; i < 10; i++) {
  10. // Prints 0 if getInteger will return null
  11. System.out.println(NullPrevent.get(getInteger()).toString());
  12. }
  13.  
  14. String[] array = null;
  15. // Returns empty array - do nothing
  16. for (String s : NullPrevent.get(String.class, array)) {
  17. System.out.println(s);
  18. }
  19. }
  20.  
  21. /**
  22.   * Returns Map with translation of some days of week.
  23.   */
  24. private static Map<String, String> getMap() {
  25. Map<String, String> map = new HashMap<>();
  26. map.put("Monday", "lunes");
  27. map.put("Tuesday", "martes");
  28. return map;
  29. }
  30.  
  31. /**
  32.   * Returns random Integer or null.
  33.   */
  34. private static Integer getInteger() {
  35. Random random = new Random(System.nanoTime());
  36. return (random.nextInt(2) == 1) ? random.nextInt() : null;
  37. }
  38. }

Look at source code of NullPrevent and download it. License ISC.

Leave a Response