【Java】頼むからDTOをしっかりと実装して欲しいお話
mokabuu
mokabuu.com
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]
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先輩にお任せしましょう。