JavaのOptionalsは、入力パラメータをチェックします

honeybadger_execute:

私は、メソッドの上に、このようなJavaの定型と入力パラメータのチェックに使用しています:

public static Boolean filesExist(String file1, String file2, String file3 ... ) {
    if (file1 == null || file2 == null || file3 == null ||...) {
        throw new IllegalArgumentException();
    }
    if (another_param == null) {
        throw new NullPointerException();
    }
}

しかし、私は、Java 8のoptionals上に読んで、私たちは、代わりにこのような何かを行うことができます気づきました。

Optional.ofNullable(file1).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(file2).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(another_param).orElseThrow(NullPointerException::new);
...

それを第二の方法を行うのいずれかの欠点がある私の質問があるので、私はそれは私には少しクリーナーに見えると感じています。

ハルク:

入力検証のために、使用Objects.requireNonNull代わりに:

public static Boolean filesExist(String file1, String file2, String file3 ... ) {
    Objects.requireNonNull(file1);
    Objects.requireNonNull(file2, "custom message");   
}

それは、より簡潔でより明確に意思を伝達し、追加作成されませんOptionalオブジェクトを。それはスローNullPointerExceptionものの、。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=231388&siteId=1