public class Foo {
private final Bar bar;
public Foo(Bar bar) {
Objects.requireNonNull(bar, "bar must not be null");
this.bar = bar;
}
}
The major advantages are:- as said, controlled behavior
- easier debugging - because you throw up in the context of the object creation. At a point in time where you have a certain chance that your logs/traces tell you what went wrong!
- and as shown above: the true power of this idea unfolds in conjunction with final fields. Because now any other code in your class can safely assume that
bar
isn’t null - and thus you do not need anyif (bar == null)
checks in other places!
개인적으로 세 번째가 가장 큰 장점이라 생각된다.
[출처]
Why should one use Objects.requireNonNull()?
0 Comments:
댓글 쓰기