Best Practices for Null‑Safe Programming in Java
To avoid NullPointerException in Java, use string literals with equals, prefer String.valueOf over toString, employ null‑safe libraries like Apache Commons StringUtils, return empty collections instead of null, annotate with @NotNull/@Nullable, prevent unnecessary autoboxing, define sensible defaults, and use Jackson's path method for safe JSON navigation.
Calling equals on a string constant Use the literal string to call .equals() (e.g., "string literal".equals(strObject) ) to avoid a NullPointerException when strObject is null . The opposite order ( strObject.equals("string literal") ) can throw the exception.
Use valueOf instead of toString BigDecimal bd = getPrice(); String.valueOf(bd); // good bd.toString(); // not good Calling toString() on a possibly null object can also cause a NullPointerException.
Use null‑safe libraries Apache Commons StringUtils provides methods that never throw NullPointerException, e.g., StringUtils.isEmpty(null) // returns true , StringUtils.isBlank(null) // returns true , StringUtils.isNumeric(null) // returns false , StringUtils.isAllUpperCase(null) // returns false .
Functions should avoid returning null , return empty objects instead Java’s Collections class offers constants such as EMPTY_LIST , EMPTY_SET , and EMPTY_MAP that can be returned from catch blocks or default paths. public List f() { try { // ... return result; } catch (SomeException e) { e.printStackTrace(); return Collections.EMPTY_LIST; } }
Use @NotNull / @Nullable annotations Adding these JSR‑305 annotations helps IDEs warn about unchecked nulls and improves code readability. Java 8 provides @NonNull ; avoid adding heavy dependencies just for the annotation.
@NonNull List strList; // A non‑null list of Strings. List<@NonNull String> strList; // A list of non‑null Strings.
Avoid unnecessary autoboxing // Integer getPrice(); int price = obj.getPrice(); If getPrice() returns Integer and the value is null , assigning it to a primitive int will throw a NullPointerException.
Define reasonable default values and leverage database NOT NULL constraints Initialize class fields with empty objects, e.g., private List intList = new ArrayList<>(); and private String str = ""; . When a database column is declared NOT NULL , you can safely use primitive types like int in Java.
public class A { private List intList = new ArrayList<>(); private String str = ""; }
Implement a class representing null (special case) For specific business logic, a dedicated “null object” can be useful. Jackson’s JSON parser demonstrates this with the path() method, which returns a MissingNode instead of null when a field is absent, allowing safe chained calls without exceptions. JsonNode root = ...; JsonNode child = root.get("lv1").get("lv2"); // may throw NPE Replace with: JsonNode root = ...; JsonNode child = root.path("lv1").path("lv2"); If lv1 is missing, path() returns a MissingNode whose subsequent path() calls also return MissingNode , preventing any NullPointerException. After processing, check with if (child.isMissingNode()) { ... } .
(Source: segmentfault)
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.