SSAFY-Book-Study / modern-java-in-action

모던 자바 인 액션 북스터디입니다.
1 stars 10 forks source link

4 Weeks - [Java의 null 처리] #57

Open hgene0929 opened 1 year ago

hgene0929 commented 1 year ago

문제

Java의 null 처리 방법에는 Optional 이외에도 requiredNonNull, assert 등이 있는 것으로 알고 있습니다. 이들과 Optional은 각각 어떻게 사용되는지 차이점이나 특징, 사용사례 등에 대해 알고싶습니다.

contents - 세부 내용

Optional을 다루는 김에 Java의 null 처리 방법에 대해 정리하고 싶습니다.

devjy39 commented 1 year ago

Null이란 무엇인가

null을 피할려면?

if(object == null) ? null 이라면..

Null handling 방법

선언과 동시에 초기화하기

Student student = new Student();

java 1.8에서 추가된 Objects 클래스의 하위 메서드 사용

if(student == null) {
    boolean isNull = true; 
} // 기존의 로직

boolean isNull = Objects.isNull(student); 
boolean isNotNull = Objects.nonNull(student);
public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}

변수 Type으로 관리

메서드 오버로딩

static class Student {
        String name;
        String certification;
        Address address;

        public Student(String name, String certification, Address address) {
            this.name = name;
            this.certification = Objects.isNull(certification) ? "없음" : certification;
            this.address = Objects.isNull(address) ? Address.isEmpty() : address;
        }
}

// 메서드 오버로딩으로 null 체크를 없애자.

public Student(String name) {
    this.name = name;
}

public Student(String name, String certification) {
    this.name = name;
    this.certification = certification;
}

public Student(String name, Address address) {
    this.name = name;
    this.address = address;
}

public Student(String name, String certification, Address address) {
    this.name = name;
    this.certification = certification;
    this.address = address;
}

비어있는 List 활용

public static final <T> List<T> emptyList() {
        return (List<T>) EMPTY_LIST;
}

// 자매품
Collections.emptyMap();
Collections.emptySet();

Optional

// private Constructor
private Optional() {
    this.value = null;
}

private Optional(T value) {
    this.value = Objects.requireNonNull(value);
}

// static factory
public static<T> Optional<T> empty() {
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
}

public static <T> Optional<T> of(T value) { // -> value에 null이 들어가면 NPE!
        return new Optional<>(value);
}

public static <T> Optional<T> ofNullable(T value) { // null 가능성이 있다면 사용
        return value == null ? empty() : of(value);
}

optional 사용 시 주의사항