continueをどう使うかという話。
ループ内で特定の条件の場合だけ処理をするようなケースで
for (Hoge hoge : hogeList) {
if (hoge.条件1()) {
if (hoge.条件2()) {
if (hoge.条件3()) {
// 実際の処理
}
}
}
}
というようにifを沢山入れ子にするよりも、
for (Hoge hoge : hogeList) {
if (!hoge.条件1()) {
continue;
}
if (!hoge.条件2()) {
continue;
}
if (!hoge.条件3()) {
continue;
}
// 実際の処理
// ...
}
というように、いわゆるガード句を利用して順次処理対象外のモノを外していく方法の方が、
ミスが少なくなるという話。
なぜミスが少なくなるのか、について考察して見ましょう。
ifの入れ子方式の場合、暗黙のelse側のルートを書き漏らすケースが出やすい。
なぜそのようなヒューマンエラーが起きやすいのか。
ひとつにはブロックが大きくなると条件式を書く場所とelseの位置が離れていくため、
対応付けを誤りやすくなるのではないかと思われます。
ガード句を利用する場合、対象外となるものを順次はずしていきますから、
ロジックを考える際の余計なものを思考から順番に外していけるため、
脳への負荷が小さくなのではないかと思います。
Iteratorパターンを使う方法
ガード句を使うほかにGoFデザインパターンのItaratorパターンを使う方法があります。
public Iterable<Hoge> hogeListFilter(List<Hoge> hogeList)
というように、Itearbleを返すメソッドなどを作り、その実装内で不要なものを除外する方法。
ちょっとしたロジックを書くには大掛かりですが、フィルタリングするロジックが
あちらこちらで同様のものを使っている場合、フィルタリング処理を分離してまとめることが出来ます。
投稿日時 : 2007年12月14日 18:40