java

【Java】サヨナラNullチェック!requireNonNullが便利すぎた!

mokabuu

こんなコード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private final static String SQL = "select NEWSONG from BANDSONGS where BANDNAME = ?";
public String getNewSong(Connection connection, String bandname) throws IOException {
    checkNull(bandname);
    try (PreparedStatement preparedStatement = connection.prepareStatement(SQL);) {
        preparedStatement.setString(1, bandname);
        try (ResultSet resultSet = preparedStatement.executeQuery();) {
            if (resultSet.next()) {
                String newSong = resultSet.getString(1);
                return newSong;
            } else {
                return null;
            }
        }
    } catch (SQLException e) {
        logger.error("Failed to get newSong!!", e);
        throw new IOException(e);
    }
}
 
private void checkNull(String bandname) {
    if (bandname == null) {
        throw new NullPointerException("bandname is null!!");
    }
}

本日こんな感じのコードを書いていると
友人が「java.Util.Objects」にいい感じのあるよと教えてくれました。

その名も「requireNonNull」先輩。

この先輩があまりに便利過ぎたので備忘録を書いておきます。


[adsense]


さっきのコードがこうなる

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private final static String SQL = "select NEWSONG from BANDSONGS where BANDNAME = ?";
public String getNewSong(Connection connection, String bandname) throws IOException {
    Objects.requireNonNull(bandname, "bandname cannot be null!!");
    try (PreparedStatement preparedStatement = connection.prepareStatement(SQL);) {
        preparedStatement.setString(1, bandname);
        try (ResultSet resultSet = preparedStatement.executeQuery();) {
            if (resultSet.next()) {
                String newSong = resultSet.getString(1);
                return newSong;
            } else {
                return null;
            }
        }
    } catch (SQLException e) {
        logger.error("Failed to get newSong!!", e);
        throw new IOException(e);
    }
}

こんな感じで
java.util.Objectsのクラスを読んでみるとこんな感じのことが書かれていました。

指定されたオブジェクト参照が null でないことを確認し、null の場合はカスタマイズされた NullPointerException をスローします。

便利すぎる!!!!!


まとめ
これからはnullチェックは全部requireNonNull先輩にお任せしましょう。

Xからの読者コメントをお待ちしています。
ブログ更新の励みになります!
スポンサーリンク

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

ABOUT ME
mokabuu
mokabuu
ブログ管理人
2014年1月からmokabuu.comを運営しております。現在10年間で老朽化したサイトをリフォーム中です(2025/1〜)。
記事URLをコピーしました