4
10

More than 5 years have passed since last update.

【SpringBoot】SpringBootを使うなら沢山入っているutilを使うと便利だった話

Last updated at Posted at 2019-01-31

タイトルで結論書いてますが、SpringBootでやっているなら、org.springframework.utilパッケージ内に設定されている色々なutil関数を使うことができて便利でした。

以下使ってみた関数と実装を2つ挙げます。

リストのnull/空チェック

実装が色々槍玉に上がっている印象があるリストのnull/空チェックですが、org.springframework.util.CollectionUtils.isEmptyで定義されています。

/**
 * Return {@code true} if the supplied Collection is {@code null} or empty.
 * Otherwise, return {@code false}.
 * @param collection the Collection to check
 * @return whether the given Collection is empty
 */
public static boolean isEmpty(@Nullable Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

ファイルの拡張子取得

ググってもGuava入れるか自力実装しろという感じで出てきますが、実装されてました。

/**
 * Extract the filename extension from the given Java resource path,
 * e.g. "mypath/myfile.txt" -> "txt".
 * @param path the file path (may be {@code null})
 * @return the extracted filename extension, or {@code null} if none
 */
@Nullable
public static String getFilenameExtension(@Nullable String path) {
    if (path == null) {
        return null;
    }

    int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
    if (extIndex == -1) {
        return null;
    }

    int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
    if (folderIndex > extIndex) {
        return null;
    }

    return path.substring(extIndex + 1);
}

結論

Springに限った話ではありませんが、自力で実装したり新しいライブラリの導入を考える前に「既に導入したライブラリのutilに実装されていないか確認する」というのは重要だと思いました。
ググラビリティが低いのでどんな関数が実装されているかというのは把握しにくいですが、個々の関数は探せば意外と見つかります。
ライブラリの実装を持ってくるなら最低限一度コードを読んでおくべきだとは思いますが、自力実装してテストする手間と比べればマシですし、勉強にもなると思います。

後、その辺も簡単に探せるideaは偉大だと思いました。

4
10
0

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
4
10