0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaのOptionalのアンチパターン

Last updated at Posted at 2025-05-03

はじめに

Optionalをnullを明示するための手段くらいにしか考えていなかった過去の私が書いていた残念コードを、アンチパターンとして記載します。

アンチパターン

アンチパターン(1)

Optionalで受け取っているのに、戻り値をnullにしてしまっている。

public static String toUpperCase(Optional<String> str) {
    if (str.isPresent()) {
        return str.get().toUpperCase();
    }
    return null;
}

アンチパターン(2)

isPresentを使って、わざわざ判定をしている

public static Optional<String> toUpperCase(Optional<String> str) {
    if (str.isPresent()) {
        return Optional.of(str.get().toUpperCase());
    }
    return Optional.empty();
}

正しい書き方

mapメソッドを使って、Optionalのまま変換処理をする

public static Optional<String> toUpperCase(Optional<String> str) {
    return str.map(String::toUpperCase);
}

Javaのサンプルコード全文

import java.util.Optional;

public class OptionalSample {

    public static Optional<String> toUpperCase(Optional<String> str) {
        return str.map(String::toUpperCase);
    }

    public static void main(String[] args) {
        final Optional<String> optional = Optional.of("hoge");
        System.out.println(toUpperCase(optional).get()); // HOGE
        final Optional<String> optional2 = Optional.empty();
        System.out.println(toUpperCase(optional2).orElse("abc")); // abc        
    }
    
}


補足

JavaのOptional型は、関数型プログラミング言語に端を発するものです (Option型やMaybe型と呼ばれる)。
関数型プログラミング言語では、手続き的ではなく宣言的に記述します。
すなわち、アンチパターンで書いたような、if文を用いた手続き的な処理をできるだけ排して書けるようになっているはずです (もちろん、Javaは手続き型の言語なので、100%命令的に書くのは難しいですが)。
Optional型を使う場合には、関数型プログラミング的に書くことを意識できるとよいですね。

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?