snuffkinの遊び場

IT関係、スポーツ、数学等に関することを、気が向いたときに書いてます。

Iterator#hasNextを使わずにIterator#nextを呼び出す、不作法者を検挙するHack

とある同僚から、「hasNextを呼ばずに、nextを使っている部下がいた」との密告を受けました。そんな上司のためのHackです。warnの第二引数はここへのリンクにするとか、貴方のお好みに合わせて変更してください。

    /**
     * @when
     *   invocation.target = {@link Iterator#next()}
     *   except {
     *     guard : {@link CtWhile}
     *     guard in invocation.ancestors
     *     condition = guard.condition
     *     condition.target = {@link Iterator#hasNext()}
     *   }
     */
    public void found(CtMethodInvocation<?> invocation,
                      Messager messager) {
        messager.warn(invocation,
                      "Iterator#hasNextを使用せずにIterator#nextを呼び出しています。");
    }

以下のようなソースはOKです。

        Iterator<String> ite = list.iterator();
        while (ite.hasNext()) {
            String str = ite.next();
            System.out.println(str);
        }

ですが、以下のようなソースは死刑台行きです。

        Iterator<String> ite = list.iterator();
        String str1 = ite.next();
        String str2 = ite.next();

こんなしょうもないものは、人間様がソースコードレビューしなくても、はじきましょう。