πŸ’» Programming

Null

Null

A special value indicating the absence of a value. A programming concept that causes NullPointerException and is known as Tony Hoare's "Billion Dollar Mistake."

πŸ“– Detailed Explanation

Null is a special value in programming that represents "absence of value." It is used to express that a variable does not reference any object, has not yet been initialized, or is intentionally empty. In databases, it is used to express an "unknown value" or an "inapplicable value," and it has a clearly different meaning from 0 or an empty string ("").

The null reference was introduced by computer scientist Tony Hoare in 1965 while he was designing the ALGOL W language. At the QCon conference in 2009, he called it the "Billion Dollar Mistake." This means that the numerous bugs, security vulnerabilities, and system crashes caused by null references over the past 40 years have resulted in costs of at least one billion dollars.

In JavaScript, there are two values that represent "absence of value": null and undefined. null indicates a case where the developer intentionally assigned "no value," while undefined indicates a state where a variable has been declared but no value has been assigned yet. These two values are equal in a == comparison but different in a === comparison.

Modern programming languages offer various approaches to Null Safety. Representative examples include Java 8+'s Optional, Kotlin's Nullable Types (?), Swift's Optional, and Rust's Option. They specify the possibility of null at compile time and enforce safe ways of handling null, thereby preventing runtime NullPointerException.

πŸ’» Code Example

Java - Null Check Patterns
// 1. 전톡적인 null 체크
public String getUserName(User user) {
    if (user != null) {
        if (user.getName() != null) {
            return user.getName();
        }
    }
    return "Anonymous";
}

// 2. Optional μ‚¬μš© (Java 8+)
public String getUserNameSafe(User user) {
    return Optional.ofNullable(user)
            .map(User::getName)
            .orElse("Anonymous");
}

// 3. Objects.requireNonNull - 방어적 ν”„λ‘œκ·Έλž˜λ°
public void processUser(User user) {
    Objects.requireNonNull(user, "User must not be null");
    // userκ°€ null이면 NullPointerException λ°œμƒ
}
JavaScript - null vs undefined
// null vs undefined 비ꡐ
let a;                    // undefined (μ„ μ–Έλ§Œ 함)
let b = null;            // null (μ˜λ„μ μœΌλ‘œ 비움)

console.log(a == b);      // true  (λŠμŠ¨ν•œ 비ꡐ)
console.log(a === b);     // false (μ—„κ²©ν•œ 비ꡐ)

// Optional Chaining (?.) - ES2020
const userName = user?.profile?.name ?? "Anonymous";

// Nullish Coalescing (??) - null/undefined만 처리
const count = inputCount ?? 0;  // 0μ΄λ‚˜ ""λŠ” κ·ΈλŒ€λ‘œ μ‚¬μš©
const count2 = inputCount || 0; // 0μ΄λ‚˜ ""도 0으둜 λŒ€μ²΄
Kotlin - Null Safety
// Kotlin의 Nullable Types
var name: String = "John"   // null λΆˆκ°€
var nullableName: String? = null  // null κ°€λŠ₯

// Safe call operator (?.)
val length = nullableName?.length  // null이면 null λ°˜ν™˜

// Elvis operator (?:)
val len = nullableName?.length ?: 0  // null이면 0

// Not-null assertion (!!) - ꢌμž₯ν•˜μ§€ μ•ŠμŒ
val forceLength = nullableName!!.length  // NPE λ°œμƒ κ°€λŠ₯

// let을 μ΄μš©ν•œ null 체크
nullableName?.let {
    println("Name length: ${it.length}")
}

πŸ—£ Practical Conversation Example

πŸ” Code Review: Preventing NullPointerException
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
The user.getAddress().getCity() part of this code looks risky. A NullPointerException can occur in situations where user or address may be null. How should we fix it?
πŸ‘©β€πŸ’»
Junior Developer
Ah, right. I think we could fix it with Optional by using Optional.ofNullable(user).map(User::getAddress).map(Address::getCity).orElse("Unknown"). Or we could also make it fail fast at the start of the method with Objects.requireNonNull.
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
Good approach! The Optional chain would be cleaner. Also, if possible, check whether address is declared as Optional in the domain model itself. Specifying the possibility of null at the API design stage is the best defense.

πŸŽ“ Technical Interview: Null Handling Strategies
πŸ‘€
Interviewer
Tony Hoare called null the "Billion Dollar Mistake." Why did he say that? And how are modern languages trying to solve this problem?
πŸ‘©
Candidate
Null references cause NPEs at runtime, leading to system failures, and preventing them requires defensive null-check code, which increases code complexity. Over decades, the costs of fixing bugs, system downtime, and security vulnerabilities resulting from this have been enormous.
πŸ‘©
Candidate
As a solution, Kotlin specifies nullable in the type system, as in String?, and the compiler enforces it. Rust has no null itself and expresses the presence or absence of a value with Option<T>. Java introduced Optional, but cannot enforce it because of compatibility with existing code.
πŸ‘€
Interviewer
Good. Then, when handling null in practice, do you have any principles of your own?
πŸ‘©
Candidate
First, methods return an empty collection or Optional instead of null whenever possible. Second, public method parameters fail fast at the start with requireNonNull. Third, fields are initialized in the constructor to minimize null states.

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠ Cautions

🚨 Practical Cautions About Null
  • NullPointerException (NPE): The most common runtime exception. An NPE in production can lead to service outages, so make use of code reviews and static analysis tools (@Nullable, @NonNull annotations).
  • Avoid overusing Optional: Optional was designed to be used as a return type. Using it as a field type, a method parameter, or a collection element actually increases complexity. Also avoid calling Optional.get() directly.
  • Defensive coding: Assume that data coming from external APIs, databases, and user input can always be null. The assumption that "this value is never null" is dangerous.
  • Distinguish null from empty values: An empty string ("") and null, and an empty list and null, have different meanings. Use them with a clear distinction between "no value" and "an empty value present."
  • Database NULL: In SQL, NULL means "unknown," and NULL = NULL is false. Use the IS NULL, COALESCE, and NULLIF functions appropriately.

πŸ”— Related Terms

πŸ“š Learn More