PMD Javaルール Best Practices

PMDのJavaルールについてまとめます。バージョン6.35.0時のルールとなっています。
非推奨となっているルールには「△」を先頭に付与しています。

バージョン6.35.0から6.47.0までのルールの差分については別の記事でまとめています。 olafnosuke.hatenablog.com

Best Practicesカテゴリには、一般に受け入れられているベストプラクティスを実施するルールが含まれている。

AbstractClassWithoutAbstractMethod

abstractクラスにabstractメソッドが記述されているか

// NG例
public abstract class Sample { // abstractメソッドも定義する

    public void doSomething() {
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AbstractClassWithoutAbstractMethod" />

△ AccessorClassGeneration

privateコンストラクタが呼び出されていないか
Java10までのルール。Java11では使えない。issue

ルール設定例

<rule ref="category/java/bestpractices.xml/AccessorClassGeneration" />

△ AccessorMethodGeneration

別のクラスからプライベート フィールド/メソッドにアクセスしていないか
Java10までのルール。Java11では使えない。issue

ルール設定例

<rule ref="category/java/bestpractices.xml/AccessorMethodGeneration" />

ArrayIsStoredDirectly

メソッドのパラメータに指定された配列をそのまま配列フィールドに設定していないか

// NG例
public class Sample {

    private String[] x;

    public void doSomething(String[] param) { // コピーした配列を設定するべき
        this.x = param;
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
allowPrivate true true の場合、privateメソッド/コンストラクターは配列をそのまま保存できるようにする -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/ArrayIsStoredDirectly" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/ArrayIsStoredDirectly">
    <properties>
        <property name="allowPrivate" value="true" />
    </properties>
</rule>

AvoidMessageDigestField

MessageDigestインスタンスをフィールドとして宣言していないか

// NG例
public class Sample {

    private final MessageDigest sharedMd;

    public Sample() throws Exception {
        sharedMd = MessageDigest.getInstance("SHA-256");
    }
}

// OK例
public class Sample {

    public byte[] doSomething(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data);
        return md.digest();
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AvoidMessageDigestField" />

AvoidPrintStackTrace

printStackTrace()が使用されていないか

// NG例
void doSomething() {
    try {
    } catch (Exception e) {
        e.printStackTrace(); // ログ出力にするべき
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace" />

AvoidReassigningCatchVariables

キャッチ変数の再割り当てをしていないか

// NG例
void doSomething() {
    try {
    } catch (Exception e) {
        e = new IllegalArgumentException(); 
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AvoidReassigningCatchVariables" />

AvoidReassigningLoopVariables

ループ変数の再割り当てをしていないか

// NG例
public class Sample {

    void doSomething() {
        for (int i = 0; i < 10; i++) {
            if (check(i)) {
                i++; 
            }

            i = 5; 
        }
    }

    boolean check(int i) {
        if (i > 5) {
            return true;
        } else {
            return false;
        }
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
foreachReassign deny foreach制御変数の再割り当ての方法と条件。
deny:ループ本体内のループ変数の再割り当てを検出
allow:ループ変数をチェックしない
firstOnly:ループ本体の最初の処理を除き、ループ変数の再割り当てを検出
-
forReassign deny どのようにして制御変数を再配置するか。
deny:ループ本体内の制御変数の再割り当てを検出
allow:制御変数をチェックしない
skip:条件付きインクリメント/デクリメント ( ++、--、+=、-=)を除く制御変数の再割り当てを検出
-

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/AvoidReassigningLoopVariables" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/AvoidReassigningLoopVariables">
    <properties>
        <property name="foreachReassign" value="deny" />
        <property name="forReassign" value="deny" />
    </properties>
</rule>

AvoidReassigningParameters

パラメーターの再割り当てをしていないか

// NG例
void doSomething(String s) {
    s = s.trim();
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AvoidReassigningParameters" />

AvoidStringBufferField

StringBuffer 型のフィールドを検出

// NG例
public class Sample {
    private StringBuffer buffer;
}

ルール設定例

<rule ref="category/java/bestpractices.xml/AvoidStringBufferField" />

AvoidUsingHardCodedIP

ハードコードされた IP アドレスがないか

// NG例
public class Sample {
    private String ip = "127.0.0.1";
}

プロパティ

名前 デフォルト値 説明 複数指定
checkAddressTypes IPv4 mapped IPv6 | IPv6 | IPv4 IPアドレスの種類を確認する。 区切り文字「|」

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/AvoidUsingHardCodedIP" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/AvoidUsingHardCodedIP">
    <properties>
        <property name="checkAddressTypes" value="IPv4 mapped IPv6|IPv6|IPv4" />
    </properties>
</rule>

CheckResultSet

ResultSetのメソッド (next、previous、first、last) の戻り値を確認しているか

// NG例
void doSomething() throws SQLException {
    Connection conn = null;
    Statement stat = conn.createStatement();
    ResultSet rst = stat.executeQuery("SELECT name FROM person");
    rst.next();
    String firstName = rst.getString(1);
}

ルール設定例

<rule ref="category/java/bestpractices.xml/CheckResultSet" />

ConstantsInInterface

インターフェイスで定数を使用していないか

// NG例
public interface Animal {
    public static final int COUNT = 50;
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoreIfHasMethods true インターフェイスがメソッドを定義する場合、インターフェイスの定数を無視するかどうか -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/ConstantsInInterface" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/ConstantsInInterface">
    <properties>
        <property name="ignoreIfHasMethods" value="true" />
    </properties>
</rule>

DefaultLabelNotLastInSwitchStmt

switch文のdefaultが最後にあるか

// NG例
void doSomething() {
    int a = 3;
    switch (a) {
    case 1:
        break;
    default:
        break;
    case 2:
        break;
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/DefaultLabelNotLastInSwitchStmt" />

DoubleBraceInitialization

ダブルブレースイニシャライゼーション(二重括弧での初期化)をしていないか

// NG例
List<String> doSomething() {
    return new ArrayList<String>() {
        {
            add("a");
            add("b");
            add("c");
        }
    };
}

// OK例
List<String> doSomething() {
    List<String> a = new ArrayList<>();
    a.add("a");
    a.add("b");
    a.add("c");
    return a;
}

ルール設定例

<rule ref="category/java/bestpractices.xml/DoubleBraceInitialization" />

ForLoopCanBeForeach

foreach 構文で置き換えることができるループを検出

// NG例
void doSomething() {
    List<String> a = new ArrayList<>();
    a.add("a");
    a.add("b");
    a.add("c");

    for (int i = 0; i < a.size(); i++) { 
        System.out.println(a.get(i));
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach" />

ForLoopVariableCount

変数が2つ以上あるforループを使用していないか

// NG例
void doSomething() {
    for (int i = 0, j = 1; i < 5; i++, j += 2) { 
        System.out.println(i + j);
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
maximumVariables 1 for文に最大いくつの制御変数を許可するか -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/ForLoopVariableCount" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/ForLoopVariableCount">
    <properties>
        <property name="maximumVariables" value="1" />
    </properties>
</rule>

GuardLogStatement

ログレベルを使用する場合はログレベルが有効になっているかどうかを確認しているか

// NG例
log.debug("log something");

// OK例
if (log.isDebugEnabled()) {
    log.debug("log something");
}

プロパティ

名前 デフォルト値 説明 複数指定
logLevels trace, debug, info, warn, error, log, finest, finer, fine, info, warning, severe 確認するログレベル コンマ区切り
guardsMethods isTraceEnabled, isDebugEnabled, isInfoEnabled, isWarnEnabled, isErrorEnabled, isLoggable ログレベルを確認するメソッド コンマ区切り

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/GuardLogStatement" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/GuardLogStatement">
    <properties>
        <property name="logLevels" value="trace,debug,info,warn,error,log,finest,finer,fine,info,warning,severe" />
        <property name="guardsMethods" value="isTraceEnabled,isDebugEnabled,isInfoEnabled,isWarnEnabled,isErrorEnabled,isLoggable" />
    </properties>
</rule>

JUnit4~はJUnit3→JUnit4でアノテーションベースになったことに対するチェック


JUnit4SuitesShouldUseSuiteAnnotation

suiteはアノテーション(@RunWith(Suite.class) )で示されているか

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnit4SuitesShouldUseSuiteAnnotation" />

JUnit4TestShouldUseAfterAnnotation

テスト終了後に行う処理は@AfterEach、@AfterAllを付与したメソッドで行う

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseAfterAnnotation" />

JUnit4TestShouldUseBeforeAnnotation

テスト終了後に行う処理は @BeforeEach 、@BeforeAll を付与したメソッドで行う

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseBeforeAnnotation" />

JUnit4TestShouldUseTestAnnotation

テストメソッドにアノテーションを付与しているか

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseTestAnnotation" />

JUnit5TestShouldBePackagePrivate

パッケージプライベートではないJUnit 5テストクラスとメソッドを検出する

// NG例
@Test
public void test() {
}

// OK例
@Test
void test() {
}

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnit5TestShouldBePackagePrivate" />

JUnitAssertionsShouldIncludeMessage

JUnit アサーションにメッセージを含めているか

// NG例
@Test
public void test() {
    assertEquals("foo", "bar");
}

// OK例
@Test
void test() {
    assertEquals("Foo does not equals bar", "foo", "bar");
}

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnitAssertionsShouldIncludeMessage" />

JUnitTestContainsTooManyAsserts

アサーションを使いすぎていないか(2つ以上でNG)

// NG例
@Test
public void test() {
    assertEquals("Foo does not equals bar", "foo", "bar");
    assertEquals("Foo does not equals bar", "foo", "bar");
}

// OK例
@Test
void test() {
    assertEquals("Foo does not equals bar", "foo", "bar");
}

プロパティ

名前 デフォルト値 説明 複数指定
maximumAsserts 1 テスト メソッド内のアサートの最大数。 -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/JUnitTestContainsTooManyAsserts" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/JUnitTestContainsTooManyAsserts">
    <properties>
        <property name="maximumAsserts" value="1" />
    </properties>
</rule>

JUnitTestsShouldIncludeAssert

テストメソッドに少なくとも1つのアサーションが含まれているか

// NG例
@Test
public void test() {
}

// OK例
@Test
void test() {
    assertEquals("Foo does not equals bar", "foo", "bar");
}

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnitTestsShouldIncludeAssert" />

JUnitUseExpected

Junit4で例外のテストに @Test(expected) を使用する

ルール設定例

<rule ref="category/java/bestpractices.xml/JUnitUseExpected" />

LiteralsFirstInComparisons

文字列比較でリテラルを最初に配置しているか

// NG例
void doSomething() {
    String s = "";
    s.equals("a");
}

// OK例
void doSomething() {
    String s = "";
    "a".equals(s);
}

ルール設定例

<rule ref="category/java/bestpractices.xml/LiteralsFirstInComparisons" />

LooseCoupling

インターフェイス(例:Set)ではなく、実体クラス(例:HashSet)で宣言している箇所がないか

// NG例
public class Sample {
    ArrayList<String> list = new ArrayList<>();
}

// OK例
public class Sample {
    List<String> list = new ArrayList<>();
}

ルール設定例

<rule ref="category/java/bestpractices.xml/LooseCoupling" />

MethodReturnsInternalArray

配列フィールドをそのまま戻り値として返却していないか

// NG例
public class Sample {
    String[] s;
    
    String[] doSomething() {
        return s; // コピーした配列を返却するべき
    }    
}

ルール設定例

<rule ref="category/java/bestpractices.xml/MethodReturnsInternalArray" />

MissingOverride

オーバーライドされたメソッドに @Override をつけているか

// NG例
public class Sample {
    
    String toString() {
    }    
}

// OK例
public class Sample {
    @Override
    String toString() {
    }    
}

ルール設定例

<rule ref="category/java/bestpractices.xml/MissingOverride" />

OneDeclarationPerLine

同じタイプの複数の変数宣言を 1 行でしていないか

// NG例
public class Sample {
    String names, lastnames; 
}

// OK例
public class Sample {
    String name; 
    String lastname;

    String namea,
           lastnamea;
}

プロパティ

名前 デフォルト値 説明 複数指定
strictMode false true の場合、宣言が別々の行にある場合でも、結合された宣言をマークする。
OK例の一番下がNGになる。
-

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/OneDeclarationPerLine" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/OneDeclarationPerLine">
    <properties>
        <property name="strictMode" value="false" />
    </properties>
</rule>

△ PositionLiteralsFirstInCaseInsensitiveComparisons

非推奨のため省略


△ PositionLiteralsFirstInComparisons

非推奨のため省略


PreserveStackTrace

スタックトレースが捨てられていないか

// NG例
void doSomething() {
    try {
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

// OK例
void doSomething() {
    try {
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/PreserveStackTrace" />

ReplaceEnumerationWithIterator

Enumerationが使用されているか

// NG例
public class Sample implements Enumeration {
    @Override
    public boolean hasMoreElements() {
        return false;
    }

    @Override
    public Object nextElement() {
        return null;
    }
}

// OK例
public class Sample implements Iterator {
    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public Object next() {
        return null;
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/ReplaceEnumerationWithIterator" />

ReplaceHashtableWithMap

Hashtableが使用されているか

// NG例
void doSomething() {
    Hashtable<String, String> h = new Hashtable<String, String>();
}

// OK例
void doSomething() {
    Map<String, String> h = new HashMap<String, String>();
}

ルール設定例

<rule ref="category/java/bestpractices.xml/ReplaceHashtableWithMap" />

ReplaceVectorWithList

Vectorが使用されているか

// NG例
void doSomething() {
    Vector<String> v = new Vector<String>();
}

// OK例
void doSomething() {
    List<String> l = new ArrayList<String>();
}

ルール設定例

<rule ref="category/java/bestpractices.xml/ReplaceVectorWithList" />

SwitchStmtsShouldHaveDefault

switch文にdefaultケースがあるか

// NG例
void doSomething() {
    int a = 3;
    switch (a) {
    case 1:
        break;
    case 2:
        break;
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/SwitchStmtsShouldHaveDefault" />

SystemPrintln

System.(out|err).print を使用しているか

// NG例
void doSomething() {
    System.out.println("qa"); //ログ出力にするべき
}

ルール設定例

<rule ref="category/java/bestpractices.xml/SystemPrintln" />

UnusedAssignment

変数が上書きされるかスコープ外になる前に使用されることのない変数がないか

public class Sample {

    private String f = "t";

    Sample(String f) {
        this.f = f;
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
checkUnusedPrefixIncrement false (i + 1) に置き換えられる可能性のある++iのような式を検出する。 -
reportUnusedVariables false 初期化されただけでまったく読み取られない変数を検出する。 -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/UnusedAssignment" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/UnusedAssignment">
    <properties>
        <property name="checkUnusedPrefixIncrement" value="false" />
        <property name="reportUnusedVariables" value="false" />
    </properties>
</rule>

UnusedFormalParameter

使用されていない引数がないか

// NG例
public class Sample {
    private void doSomething(int r) { //使用しないなら削除する

    }
}

プロパティ

名前 デフォルト値 説明 複数指定
checkAll false プライベートでないものを含むすべてのメソッドをチェックする -

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter">
    <properties>
        <property name="checkAll" value="false" />
    </properties>
</rule>

△ UnusedImports

非推奨のため省略


UnusedLocalVariable

使用されていないローカル変数がないか

// NG例
public class Sample {
    void doSomething(String p) {
        String s = "a"; //使用しないなら削除する
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UnusedLocalVariable" />

UnusedPrivateField

使用されていないプライベートフィールドがないか

// NG例
public class Sample {
    private String t = "t"; //使用しないなら削除する

    void doSomething(String p) {
        String s = "a";
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations lombok.Setter| lombok.Getter| lombok.Builder| lombok.Data| lombok.RequiredArgsConstructor| lombok.AllArgsConstructor| lombok.Value| lombok.NoArgsConstructor| java.lang.Deprecated| javafx.fxml.FXML| lombok.experimental.Delegate| lombok.EqualsAndHashCode このルールで無視する必要がある注釈タイプの完全修飾名。 「|」区切り

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/UnusedPrivateField" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/UnusedPrivateField">
    <properties>
        <property name="ignoredAnnotations" value="lombok.Setter|lombok.Getter|lombok.Builder|lombok.Data|lombok.RequiredArgsConstructor|lombok.AllArgsConstructor|lombok.Value|lombok.NoArgsConstructor|java.lang.Deprecated|javafx.fxml.FXML|lombok.experimental.Delegate|lombok.EqualsAndHashCode" />
    </properties>
</rule>

UnusedPrivateMethod

使用されていないプライベートメソッドがないか

// NG例
public class Sample {
    void doSomething(String p) {
        String s = "a";
    }

    private void doSomething() { //使用しないなら削除する
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations java.lang.Deprecated このルールで無視する必要がある注釈タイプの完全修飾名 「|」区切り

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod">
    <properties>
        <property name="ignoredAnnotations" value="java.lang.Deprecated" />
    </properties>
</rule>

UseAssertEqualsInsteadOfAssertTrue

assertTrueよりもassertEqualsがふさわしい検証はないか

// NG例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        Sample s2 = new Sample();
        assertTrue(s.equals(s2));
    }
}

// OK例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        Sample s2 = new Sample();
        assertEquals(s, s2);
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseAssertEqualsInsteadOfAssertTrue" />

UseAssertNullInsteadOfAssertTrue

assertTrueよりもassertNullがふさわしい検証はないか

// NG例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        assertTrue(s == null);
    }
}

// OK例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        assertNull(s);
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseAssertNullInsteadOfAssertTrue" />

UseAssertSameInsteadOfAssertTrue

assertTrueよりもassertSameがふさわしい検証はないか

// NG例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        Sample s2 = new Sample();
        assertTrue(s == s2);
    }
}

// OK例
class SampleTest {

    @Test
    void test() {
        Sample s = new Sample();
        Sample s2 = new Sample();
        assertSame(s, s2);
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseAssertSameInsteadOfAssertTrue" />

UseAssertTrueInsteadOfAssertEquals

assertEqualsよりもassertTrueがふさわしい検証はないか

// NG例
class SampleTest {

    @Test
    void test() {
        boolean b = true;
        assertEquals(b, true);
    }
}

// OK例
class SampleTest {

    @Test
    void test() {
        boolean b = true;
        assertTrue(b);
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseAssertTrueInsteadOfAssertEquals" />

UseCollectionIsEmpty

コレクションが空であることを確認する時はisEmpty()を使用するべき

// NG例
public class Sample {

    void doSomething() {
        List<String> list = new ArrayList<String>();
        if (list.size() == 0) {
        }
    }
}

// OK例
public class Sample {

    void doSomething() {
        List<String> list = new ArrayList<String>();
        if (list.isEmpty()) {

        }
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseCollectionIsEmpty" />

UseStandardCharsets

一般的な Charset オブジェクトの定数を使用するべき

// NG例
public class Sample {

    void doSomething() {

        File file = new File("test");
        try (BufferedReader reader = new BufferedReader(new FileReader(file, Charset.forName("UTF-8")))) {
        } catch (Exception e) {
        }
    }
}

// OK例
public class Sample {

    void doSomething() {

        File file = new File("test");
        try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
        } catch (Exception e) {
        }
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseStandardCharsets" />

UseTryWithResources

try-with-resources ステートメントを使用するべき

// NG例
public class Sample {

    void doSomething() {
        File file = new File("test");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
        } catch (Exception e) {
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

// OK例
public class Sample {

    void doSomething() {
        File file = new File("test");
        try (BufferedReader reader = new BufferedReader(new FileReader(file)) {
        } catch (Exception e) {
        }
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
allowPrivate close, closeQuietly このルールをトリガーする、finally ブロック内のメソッド名。 コンマ区切り

ルール設定例

<!-- プロパティ設定なし -->
<rule ref="category/java/bestpractices.xml/UseTryWithResources" />

<!-- プロパティ設定あり -->
<rule ref="category/java/bestpractices.xml/UseTryWithResources">
    <properties>
        <property name="closeMethods" value="close,closeQuietly" />
    </properties>
</rule>

UseVarargs

可変長引数の利用

// NG例
public class Sample {
    void doSomething(String s, int[] args) {
    }
}

// OK例
public class Sample {
    void doSomething(String s, int... args) {
    }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/UseVarargs" />

WhileLoopWithLiteralBoolean

true,falseが直書きされているwhile文はないか

// NG例
public class Sample {

    void doSomething() {
        while (true) {
            break;
        }
}

ルール設定例

<rule ref="category/java/bestpractices.xml/WhileLoopWithLiteralBoolean" />

他のカテゴリのルールもまとめています。

Code Styleカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Designカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Documentationカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Error Proneカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Multithreadingカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Performanceカテゴリのまとめはこちら: olafnosuke.hatenablog.com

Securityカテゴリのまとめはこちら: olafnosuke.hatenablog.com