-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
4 Weeks - [Java의 null 처리] #57
Comments
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 사용 시 주의사항
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
문제
Java의 null 처리 방법에는 Optional 이외에도 requiredNonNull, assert 등이 있는 것으로 알고 있습니다.
이들과 Optional은 각각 어떻게 사용되는지 차이점이나 특징, 사용사례 등에 대해 알고싶습니다.
contents - 세부 내용
Optional을 다루는 김에 Java의 null 처리 방법에 대해 정리하고 싶습니다.
The text was updated successfully, but these errors were encountered: