java には Optional のクラスがあり、Null を予防することができる。以下のように使う。
import java.util.List;
import java.util.Arrays;
import java.util.Optional;
public class IntegerList {
private final static List<Integer> values = Arrays.asList(new Integer[]{1, 2, null});
public static Optional<Integer> get(int index) {
return Optional.ofNullable(values.get(index));
}
}
//呼び出し側
Optional<Integer> optionalValue = IntegerList.get(2);
Integer value = optionalValue.orElse(-1) + 100; //orElseはNullである時指定されている値を返す
System.out.println("結果:" + value);
//値がNullであるかを判定するには以下のように記載し、値が存在する場合はtrueを返す。
optionalValue.isPresent()
//選択された例外をスローさせる
optionalValue.oeElseThrow(() -> new NotFoundException("not found id" + id))
//値があるとわかっているときはgetを使う
optionalValue.get()
//リストのnullを弾く
streamOptionals.filter(Optional::isPresent).map(Optional::get); //filterで値があるものだけを条件とし、mapで値を取り出す。具体的には、Stream<T>の引数を取り出すことになる。
IntergerList のクラスで values を取り出すクラスの get があるとする。Optional を利用し、Optional を返すことで Null があることを知らせる。これの良いところは、返される値に Null が許可されているかを明示的に知ることができるところである。
API を適切に文章化するには、全ての公開されているクラス、インタフェース、コンストラクタ、メソッドフィールド宣言の前にドキュメンテーションを書く必要がある。 Java には JavaDoc は HTML 形式で表示してくれる説明書のようなものである。以下が例。
//List.get()
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
E get(int index);
List の get を例である。
ジェネリクスで定義されているメソッドを文章化するときは全てのパラメータを文章化する必要がある
//Map.java
/**
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*
*/
public interface Map<K, V>
enum も列挙した奴の意味を記載する
public enum OrchestraSection{
/** 木管楽器, フルートやクラリネット */
WOODWIND,
/** 金管楽器, ホルンやトランペット*/
BRASS,
PRECUSSION,
STRING
}
最後に、複雑は API のクラスやメソッドなどで外部の設計を参照する必要がある場合は、そのリンクを docs に記載しておく必要がある。
ローカル変数のスコープを最小限にする最も強力な技法は、ローカル変数が初めて使われたときに宣言すること。単純にいえば、必要になった時に宣言していれば良い。また、そのときは初期化子を含め定義しておくことが望ましい。
List<String> words = null;
or
List<String> words = new ArrayList<>();
上記のような形で宣言しておき、初期化子を含める。