NPE xảy ra khi gọi method/truy cập field/unbox primitive trên reference null.
Tony Hoare gọi null là "lỗi tỷ đô" của mình.
String s = null;
s.length(); // NPE
Map<String, Integer> m = Map.of("a", 1);
int x = m.get("b"); // NPE — unbox Integer null thành intPhòng tránh, theo độ ưu tiên:
1. Thiết kế không nhận/trả null: dùng Optional<T>, list rỗng List.of(), hoặc throw exception. Cách bền nhất.
2. Objects.requireNonNull(arg) ở đầu constructor/method → fail-fast ngay tại biên giới.
3. Optional<T> cho return type — không dùng làm field/parameter.
4. JDK 14+ "Helpful NPE": message chỉ rõ biến nào null (mặc định bật từ JDK 15).
5. @NonNull/@Nullable (JSpecify, Checker Framework): IDE cảnh báo lúc edit.
6. Pattern matching instanceof (Java 16+): auto null-check + cast.
Tránh:
- map.get() rồi dùng ngay mà không check.
- Optional.get() không check isPresent() — chỉ đổi NPE thành NoSuchElementException.
Chốt: đừng rải if (x != null) khắp nơi — thiết kế contract để null không đi vào hệ thống ngay từ đầu.
NPE is thrown when you invoke a method, access a field, or unbox a primitive on a null reference.
Tony Hoare famously called null his "billion-dollar mistake".
String s = null;
s.length(); // NPE
Map<String, Integer> m = Map.of("a", 1);
int x = m.get("b"); // NPE — unboxing Integer null to intPrevention, by preference:
1. Design APIs that never accept/return null: return Optional<T>, an empty list, or throw. Most durable.
2. Objects.requireNonNull(arg) at the top of constructors/methods → fail-fast at the boundary.
3. Optional<T> for return types — not for fields or parameters.
4. JDK 14+ "Helpful NPE": message points to the null reference (on by default since JDK 15).
5. @NonNull/@Nullable (JSpecify, Checker Framework): IDE warns at edit time.
6. Pattern matching instanceof (Java 16+): auto null-checks and casts.
Avoid:
- Using map.get() results without checking.
- Optional.get() without isPresent() — just swaps NPE for NoSuchElementException.
Bottom line: do not litter if (x != null) everywhere — design contracts so null never enters the system.