LoginSignup
16
19

More than 5 years have passed since last update.

メソッド内でパラメータの値チェックを行う

Last updated at Posted at 2012-06-30

Google GuavaライブラリのPreconditionsクラスのメソッド達が便利です。
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html

nullチェック

例えば、こんな感じでメソッドの先頭でパラメータの値がnullかどうかをチェックしたい事はよくあると思います。

if文を使ってパラメータチェックをする場合
public void doSomething(String message) {
    if(message == null) {
        throw new NullPointerException("message must not be null.");
    }
    this.message = message;
}

いちいちif文を書くのが面倒ですが、Guavaライブラリを使うとこんな感じですっきり書くことが出来るようになります。

checkNotNullを使用する場合
public void doSomething(String message) {
    this.message = checkNotNull(message, "message must not be null");
}

もし、messageがnullだった場合は、checkNotNullの第2引数をエラーメッセージとしたNullPointerExceptionが投げられます。

さらに、nullではなかった場合は、messageの値をそのまま返してくれるので、続けてcheckNotNullの返り値を使うことも出来ます。

bool値を返す式によるチェック

他にも、bool値を返す式を引数に渡し、それが偽だった場合は例外を投げてくれるcheckArgumentのようなメソッドも用意されています。

checkArgument
public void doSomethingElse(int value) {
    checkArgument(value > 0, "Expected positive but value was %s", value);
}

これは、valueに0以下の値が渡された場合、IllegalArgumentExceptionが投げられます。

おまけ

Preconditionsで定義されている上記のメソッドはスタティックメソッドなので、static import剃る必要があります。
Eclipseでstatic importを簡単に書く方法はこちらにまとめています。
Eclipseでstatic importを簡単に扱う方法

16
19
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
19