PMD Javaルール Code Style

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

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

Code Styleカテゴリには、特定のコーディングスタイルを強制するルールが含まれている。

△AbstractNaming

非推奨のため省略


AtLeastOneConstructor

クラスの中で少なくとも1つのコンストラクタが宣言されているか

// NG
public class Sample {
    static void doSomething() {
    }
}

// OK
public class Sample {
    public Sample(){
    }
    
    static void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations lombok.Data| lombok.Value| lombok.Builder| lombok.NoArgsConstructor| lombok.RequiredArgsConstructor| lombok.AllArgsConstructor このルールで無視するアノテーションの完全修飾名 「|」区切り

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/AtLeastOneConstructor">
    <properties>
        <property name="ignoredAnnotations" value="lombok.Data|lombok.Value|lombok.Builder|lombok.NoArgsConstructor|lombok.RequiredArgsConstructor|lombok.AllArgsConstructor" />
    </properties>
</rule>

AvoidDollarSigns

メソッド名、クラス名、変数名に$が含まれていない

// NG
String doller$ = "aaa";

ルール設定例

<rule ref="category/java/codestyle.xml/AvoidDollarSigns" />

△AvoidFinalLocalVariable

非推奨のため省略


△AvoidPrefixingMethodParameters

非推奨のため省略


AvoidProtectedFieldInFinalClass

finalクラスでprotectedフィールドが宣言されていないか
privateかパッケージプライベートにする

// NG
public final class Sample {
    protected int y;
}

ルール設定例

<rule ref="category/java/codestyle.xml/AvoidProtectedFieldInFinalClass" />

AvoidProtectedMethodInFinalClassNotExtending

finalクラスでprotectedメソッドが定義されていないか
privateかパッケージプライベートにする

// NG
public final class Sample {
    protected void doSomething() {
    }
}

ルール設定例

<rule ref="category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending" />

AvoidUsingNativeCode

ネイティブコードの使用を避ける

// NG
void doSomething() {
    System.loadLibrary("nativelib");
}

ルール設定例

<rule ref="category/java/codestyle.xml/AvoidUsingNativeCode" />

BooleanGetMethodName

booleanのgetterのメソッド名にgetを使用しない

// NG
public class Sample {
    private boolean select;

    public boolean getSelect() {
        return select;
    }
}

// OK
public class Sample {
    private boolean select;

    public boolean isSelect() {
        return select;
    }
    
    public boolean getSelect(boolean bar){ // checkParameterizedMethodsをtrueにした場合はNGになる
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
checkParameterizedMethods false パラメーター化されたメソッドをチェックする -

ルール設定例

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

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

CallSuperInConstructor

継承しているクラスでコンストラクタでsuper()もしくは別のコンストラクタが呼ばれていること
呼ばないとコンパイルエラーになる。

// NG
public class Sample extends Parent {
    public Sample (){
    }
}

// OK
public class Sample extends Parent {
    public Sample (){
        super();
    }
}

ルール設定例

<rule ref="category/java/codestyle.xml/CallSuperInConstructor" />

ClassNamingConventions

クラスの命名規則を守っているか
デフォルトでは、クラスが大文字始まりであることと、ユーティリティクラスは*Utilで終わることをチェックしている。

// NG
public class sample {
}

public class Myclass {

    private Myclass() {
    }

    public static void doSomething() {
    }
}

// OK
public class Sample {
}

public class MyclassUtil {

    private MyclassUtil() {
    }

    public static void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
classPattern [AZ][a-zA-Z0-9]* クラス名に適用される正規表現 -
abstractClassPattern [AZ][a-zA-Z0-9]* 抽象クラス名に適用される正規表現 -
interfacePattern [AZ][a-zA-Z0-9]* インターフェイス名に適用される正規表現 -
enumPattern [AZ][a-zA-Z0-9]* enumに適用される正規表現 -
annotationPattern [AZ][a-zA-Z0-9]* アノテーションに適用される正規表現 -
utilityClassPattern [AZ][a-zA-Z0-9]+(Utils?|Helper|Constants) ユーティリティクラス名に適用される正規表現 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/ClassNamingConventions">
    <properties>
        <property name="classPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="abstractClassPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="interfacePattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="enumPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="annotationPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="utilityClassPattern" value="[A-Z][a-zA-Z0-9]+(Utils?|Helper|Constants)" />
    </properties>
</rule>

CommentDefaultAccessModifier

パッケージプライベートなアノテーション、クラス、enum、メソッド、コンストラクタ、フィールドの宣言の最初にコメントを追加するべき
追加するコメントはデフォルトで/* default */もしくは/* package */である必要がある

// NG
public class Sample {
    void doSomething() {
    }
}

// OK
public class Sample {
    /* default */ void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations com.google.common.annotations.VisibleForTesting| android.support.annotation.VisibleForTesting このルールで無視するアノテーションの完全修飾名 「|」区切り
regex \/*\s+(default|package)\s+*\/ 正規表現 -
checkTopLevelTypes false トップレベルのクラス、アノテーション、および列挙型のデフォルトのアクセス修飾子を確認する -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/CommentDefaultAccessModifier">
    <properties>
        <property name="ignoredAnnotations" value="com.google.common.annotations.VisibleForTesting|android.support.annotation.VisibleForTesting" />
        <property name="regex" value="\/\*\s+(default|package)\s+\*\/" />
        <property name="checkTopLevelTypes" value="false" />
    </properties>
</rule>

ConfusingTernary

if~elseの条件式内で否定は使わない

// NG
void doSomething() {
    boolean a = true;
    boolean b = false;

    if (a != b) {
        // 処理A
    } else {
        // 処理B
    }
}

// OK
void doSomething() {
    boolean a = true;
    boolean b = false;

    if (a == b) {
        // 処理B
    } else {
        // 処理A
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoreElseIf false else-ifの場合条件を無視する -

ルール設定例

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

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

ControlStatementBraces

for, while, if, if~elseで{}をつける

// NG
void doSomething() {
    int i = 1;

    if (i == 1)
       i++;
}

// OK
void doSomething() {
    int i = 1;

    if (i == 1){
       i++;
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
checkIfElseStmt true if~elseで中括弧を使用する -
checkSingleIfStmt true 単一のif文で中括弧を使用する -
checkWhileStmt true whileループで中括弧を使用する -
checkForStmt true forループは中括弧を使用する -
checkDoWhileStmt true do…whileループで中括弧を使用する -
checkCaseStmt false スイッチのケースで中括弧を使用する -
allowEmptyLoop false while(true);などの空のステートメントでのループを許可する -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/ControlStatementBraces">
    <properties>
        <property name="checkIfElseStmt" value="true" />
        <property name="checkSingleIfStmt" value="true" />
        <property name="checkWhileStmt" value="true" />
        <property name="checkForStmt" value="true" />
        <property name="checkDoWhileStmt" value="true" />
        <property name="checkCaseStmt" value="false" />
        <property name="allowEmptyLoop" value="false" />
    </properties>
</rule>

△DefaultPackage

非推奨のため省略


△DontImportJavaLang

非推奨のため省略


△DuplicateImports

非推奨のため省略


EmptyMethodInAbstractClassShouldBeAbstract

抽象クラスの空または自動生成されたメソッドにはabstractメソッドにするべき

// NG
public abstract class Sample {
    /* default */ void doSomething() {
    }
}

// OK
public abstract class Sample {
    /* default */ abstract void doSomething();
}

ルール設定例

<rule ref="category/java/codestyle.xml/EmptyMethodInAbstractClassShouldBeAbstract" />

ExtendsObject

Objectを明示的に継承しない

// NG
public  class Sample extends Object {
}

// OK
public  class Sample {
}

ルール設定例

<rule ref="category/java/codestyle.xml/ExtendsObject" />

FieldDeclarationsShouldBeAtStartOfClass

フィールドの宣言はクラスの一番頭の部分で行う

// NG
public class Sample {
    public void doSomething() {
    }

    public String str;
}

// OK
public class Sample {
    public String str;
    
    public void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoreEnumDeclarations true フィールドの前にあるenum宣言を無視する -
ignoreAnonymousClassDeclarations true 匿名クラス宣言で初期化されるフィールド宣言を無視する -
ignoreInterfaceDeclarations false フィールドの前にあるインターフェイス宣言を無視する -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass">
    <properties>
        <property name="ignoreEnumDeclarations" value="true" />
        <property name="ignoreAnonymousClassDeclarations" value="true" />
        <property name="ignoreInterfaceDeclarations" value="false" />
    </properties>
</rule>

FieldNamingConventions

フィールド名の命名規則を守っているか
デフォルトではJava標準の命名規則(キャメルケース)を使用。定数、enumはALL_UPPER 規則を使用。

// NG
public class Sample {
    public String first_name;

    public static final String MyName = "Bob";
}

// OK
public class Sample {

    public String firstName;

    public static final String MY_NAME = "Bob";

    public void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
publicConstantPattern [AZ][A-Z_0-9]* パブリック定数名に適用される正規表現 -
constantPattern [AZ][A-Z_0-9]* 定数名に適用される正規表現 -
enumConstantPattern [AZ][A-Z_0-9]* enum定数名に適用される正規表現 -
finalFieldPattern [AZ][A-Z_0-9]* finalフィールド名に適用される正規表現 -
staticFieldPattern [AZ][A-Z_0-9]* staticフィールド名に適用される正規表現 -
defaultFieldPattern [AZ][A-Z_0-9]* 静的フィールド名に適用される正規表現 -
exclusions serialVersionUID| serialPersistentFields 除外対象のフィールドの名前。 「|」区切り

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/FieldNamingConventions">
    <properties>
        <property name="publicConstantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="constantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="enumConstantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="finalFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="staticFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="defaultFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="exclusions" value="serialVersionUID|serialPersistentFields" />
    </properties>
</rule>

ForLoopShouldBeWhileLoop

whileでも実現可能なforループがないか

// NG
public void doSomething() {
    for (; true;) {
    }
}

// OK
public void doSomething() {
    while (true) {
    }
}

ルール設定例

<rule ref="category/java/codestyle.xml/ForLoopShouldBeWhileLoop" />

△ForLoopsMustUseBraces

非推奨のため省略


FormalParameterNamingConventions

メソッドやラムダ式で仮引数名の命名規則を守っているか
デフォルトではJava標準の命名規則(キャメルケース)を使用。

// NG
public void doSomething(String your_name) {
    Consumer<String> lambda = my_name -> {
    };
}

// OK
public void doSomething(String yourName) {
    Consumer<String> lambda = myName -> {
    };
}

プロパティ

名前 デフォルト値 説明 複数指定
methodParameterPattern [az][a-zA-Z0-9]* 仮引数名に適用する正規表現 -
finalMethodParameterPattern [az][a-zA-Z0-9]* finalな仮引数名に適用する正規表現 -
lambdaParameterPattern [az][a-zA-Z0-9]* ラムダ式の引数名に適用する正規表現 -
explicitLambdaParameterPattern [az][a-zA-Z0-9]* ラムダ式で明示的に型付けされた引数名に適用する正規表現 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/FormalParameterNamingConventions">
    <properties>
        <property name="methodParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="finalMethodParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="lambdaParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="explicitLambdaParameterPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

GenericsNaming

一般的な型パラメータの参照名は英語大文字1文字にするべき

// NG
public class Sample<t extends Book> {
}
public class Sample<TA extends Book> {
}

// OK
public class Sample<T extends Book> {
}

ルール設定例

<rule ref="category/java/codestyle.xml/GenericsNaming" />

IdenticalCatchBranches

同一の処理を行うキャッチ節を複数書かない

// NG
public void doSomething() {
    try {
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (IllegalStateException e) {
        throw e;
    } catch (NullPointerException e) {
        throw e;
    }
}

// OK
public void doSomething() {
    try {
    } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
        throw e;
    } 
}

ルール設定例

<rule ref="category/java/codestyle.xml/IdenticalCatchBranches" />

△IfElseStmtsMustUseBraces

非推奨のため省略


△IfStmtsMustUseBraces

非推奨のため省略


LinguisticNaming

変数名、メソッド名と型に不和がないか
boolean値を持ちそうな名前の変数がbooleanでなかったり、booleanを返しそうなメソッドなのに違う型を返すメソッドを検出する。
getterが戻り値があってsetterに戻り値がないことも確認する。

// NG
public class Sample {
    int isSelected;

    public int isExist() {
        return 1;
    }

    public String setName() {
        return "";
    }

    public void getName() {

    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations java.lang.Override このルールで無視するアノテーションの完全修飾名 「|」区切り
checkBooleanMethod true メソッド名と型に一貫性のない名前がないか確認するか -
checkGetters true getterの戻り型を確認するか -
checkSetters true setterの戻り型を確認するか -
checkPrefixedTransformMethods true 指定されたプレフィックスで始まる名前のメソッドの戻り型を確認するか -
checkTransformMethods false 指定されたインフィックスを含むメソッドの戻り型を確認するか -
booleanMethodPrefixes is| has| can| have| will| should booleanを返すメソッドのプレフィックス 「|」区切り
transformMethodNames to|as 変換メソッドを示すプレフィックスとインフィックス 「|」区切り
checkFields true フィールド名と型に一貫性のない名前がないか確認する -
checkVariables true ローカル変数の名前と型に一貫性のない名前がないか確認する -
booleanFieldPrefixes is| has| can| have| will| should booleanを示すフィールドと変数のプレフィックス 「|」区切り

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/LinguisticNaming">
    <properties>
        <property name="ignoredAnnotations" value="java.lang.Override" />
        <property name="checkBooleanMethod" value="true" />
        <property name="checkGetters" value="true" />
        <property name="checkSetters" value="true" />
        <property name="checkPrefixedTransformMethods" value="true" />
        <property name="checkTransformMethods" value="false" />
        <property name="booleanMethodPrefixes" value="is|has|can|have|will|should" />
        <property name="transformMethodNames" value="to|as" />
        <property name="checkFields" value="true" />
        <property name="checkVariables" value="true" />
        <property name="booleanFieldPrefixes" value="is|has|can|have|will|should" />
    </properties>
</rule>

LocalHomeNamingConvention

javax.ejb.EJBLocalHomeを継承したインターフェースにはLocalHomeという接尾辞をつける必要がある

// NG
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {
}

// OK
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {
}

ルール設定例

<rule ref="category/java/codestyle.xml/LocalHomeNamingConvention" />

LocalInterfaceSessionNamingConvention

javax.ejb.EJBLocalObjectを継承したインターフェースにはLocalという接尾辞をつける必要がある

// NG
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {
} 

// OK
public interface MyLocal extends javax.ejb.EJBLocalObject {
}

ルール設定例

<rule ref="category/java/codestyle.xml/LocalInterfaceSessionNamingConvention" />

LocalVariableCouldBeFinal

一度しか使われていないローカル変数名がfinalで宣言されているか

// NG
public void doSomething() {
    String str = "str";
    System.out.println(str);
}

// OK
public void doSomething() {
    final String str = "str";
    System.out.println(str);
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoreForEachDecl false for-eachでfinalでないループ変数を無視するか 「|」区切り

ルール設定例

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

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

LocalVariableNamingConventions

ローカル変数の命名規則を守っているか
デフォルトではJava標準の命名規則(キャメルケース)を使用。

// NG
public void doSomething() {
    String my_name = "Bob";
}

// OK
public void doSomething() {
    String myName = "Bob Bob";
}

プロパティ

名前 デフォルト値 説明 複数指定
localVarPattern [az][a-zA-Z0-9]* finalでないローカル変数に適用される正規表現 -
finalVarPattern [az][a-zA-Z0-9]* finalローカル変数に適用される正規表現 -
catchParameterPattern [az][a-zA-Z0-9]* 例外ブロックのパラメータ名に適用される正規表現 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/LocalVariableNamingConventions">
    <properties>
        <property name="localVarPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="finalVarPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="catchParameterPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

LongVariable

変数名が長すぎないか
デフォルトでは17を超えると検出される

// NG
public class Sample {

    public int tameshinitsuketaNagaiNamae;

    public void doSomething(String yourFirstNameAndLastName) {
        String myFirstNameAndLastName = "Bob";
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
minimum 17 変数名の最大値 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/LongVariable">
    <properties>
        <property name="minimum" value="17" />
    </properties>
</rule>

MDBAndSessionBeanNamingConvention

MessageDrivenBeanもしくはSessionBeanの実装クラスはBeanという接尾辞をつける必要がある

// NG
public class MissingTheProperSuffix implements SessionBean {
}

// OK
public class SomeBean implements SessionBean{
}

ルール設定例

<rule ref="category/java/codestyle.xml/MDBAndSessionBeanNamingConvention" />

MethodArgumentCouldBeFinal

メソッド内で再割り当てされないメソッド引数はfinalで宣言する

// NG
public void doSomething(String yourName) {
    System.out.println(yourName);
}

// OK
public void doSomething(final String yourName) {
    System.out.println(yourName);
}

ルール設定例

<rule ref="category/java/codestyle.xml/MethodArgumentCouldBeFinal" />

MethodNamingConventions

メソッドの命名規則を守っているか
デフォルトではJava標準の命名規則(キャメルケース)を使用。

// NG
public class Sample {
    public void do_something() {
    }

    public void DoSomething() {
    }
}

// OK
public class Sample {
    public void doSomething() {
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
methodPattern [az][a-zA-Z0-9]* メソッド名に適用される正規表現 -
staticPattern [az][a-zA-Z0-9]* staticメソッド名に適用される正規表現 -
nativePattern [az][a-zA-Z0-9]* ネイティブメソッド名に適用される正規表現 -
junit3TestPattern test[az][a-zA-Z0-9]* Junit3のテストメソッド名に適用される正規表現 -
junit4TestPattern [az][a-zA-Z0-9]* Junit4のテストメソッド名に適用される正規表現 -
junit5TestPattern [az][a-zA-Z0-9]* Junit5のテストメソッド名に適用される正規表現 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/MethodNamingConventions">
    <properties>
        <property name="methodPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="staticPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="nativePattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="junit3TestPattern" value="test[A-Z0-9][a-zA-Z0-9]*" />
        <property name="junit4TestPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="junit5TestPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

△MIsLeadingVariableName

非推奨のため省略


NoPackage

パッケージのないクラス、インターフェース、enumアノテーションがないか

// NG

public class MyClass {
}

// OK
package jp.co.sample;

public class MyClass {
}

ルール設定例

<rule ref="category/java/codestyle.xml/NoPackage" />

OnlyOneReturn

メソッドの最後以外にreturnを書かない

// NG
public boolean doSomething() {
     int i = 3;

     if (i < 3) {
         return false;
     }
     return true;
}

ルール設定例

<rule ref="category/java/codestyle.xml/OnlyOneReturn" />

PackageCase

パッケージに大文字は書かない

// NG
package jp.co.Sample;

// OK
package jp.co.sample;

ルール設定例

<rule ref="category/java/codestyle.xml/PackageCase" />

PrematureDeclaration

ローカル変数の宣言が早いところがないか

// NG
public int doSome(int number) {
    int count = 0;

    if (number == 3) {
        return 3;
    }

    if (number != 3) {
        count += number;
    }
    return count;
}

// OK
public int doSome(int number) {
    if (number == 3) {
        return 3;
    }

    int count = 0;
    if (number != 3) {
        count += number;
    }
    return count;
}

ルール設定例

<rule ref="category/java/codestyle.xml/PrematureDeclaration" />

RemoteInterfaceNamingConvention

EJBObjectを継承したインターフェイス名はSessionEJBBeanをつけない

// NG
public interface BadSuffixSession extends javax.ejb.EJBObject {
}
public interface BadSuffixEJB extends javax.ejb.EJBObject {
}
public interface BadSuffixBean extends javax.ejb.EJBObject {
}

ルール設定例

<rule ref="category/java/codestyle.xml/RemoteInterfaceNamingConvention" />

RemoteSessionInterfaceNamingConvention

EJBHome を継承したインターフェイス名はHomeで終わるようにする

// NG
public interface MissingProperSuffix extends javax.ejb.EJBHome {
} 

// OK
public interface MyBeautifulHome extends javax.ejb.EJBHome {
} 

ルール設定例

<rule ref="category/java/codestyle.xml/RemoteSessionInterfaceNamingConvention" />

ShortClassName

クラス名が短すぎる
デフォルトでは5文字未満のクラス名が検出される

// NG
public class Book {
}

// OK
public class Animal {
}

プロパティ

名前 デフォルト値 説明 複数指定
minimum 5 クラス名の最小文字数 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/ShortClassName">
    <properties>
        <property name="minimum" value="5" />
    </properties>
</rule>

ShortMethodName

メソッド名が短すぎる
デフォルトでは3文字未満のメソッド名が検出される

// NG
public void a() {
}

// OK
public void send() {
}

プロパティ

名前 デフォルト値 説明 複数指定
minimum 3 メソッド名の最小文字数 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/ShortMethodName">
    <properties>
        <property name="minimum" value="3" />
    </properties>
</rule>

ShortVariable

変数名が短すぎる
デフォルトでは3文字未満の変数名が検出される

// NG
public void doSomething() {
     int i = 3;
}

// OK
public void doSomething() {
     int count = 3;
}

プロパティ

名前 デフォルト値 説明 複数指定
minimum 3 変数名の最小文字数 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/ShortVariable">
    <properties>
        <property name="minimum" value="3" />
    </properties>
</rule>

△SuspiciousConstantFieldName

非推奨のため省略


TooManyStaticImports

static インポートが多すぎる
デフォルトでは5個以上で検知される

// NG
import static Lennon;
import static Ringo;
import static George;
import static Paul;
import static Yoko;

プロパティ

名前 デフォルト値 説明 複数指定
maximumStaticImports 4 許容するstaticインポートの数。 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/TooManyStaticImports">
    <properties>
        <property name="maximumStaticImports" value="4" />
    </properties>
</rule>

UnnecessaryAnnotationValueElement

アノテーションの属性が1つしかない場合にvalueを使用しない

// NG
@Max(value = 3)
private int age;

// OK
@Max(3)
private int age;

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryAnnotationValueElement" />

UnnecessaryCast

不必要なキャストをしていないか

// NG
public void doSomething() {
    List<String> list = List.of("abc", "bcd", "cde");
    String string = (String) list.get(0);
}

// OK
public void doSomething() {
    List<String> list = List.of("abc", "bcd", "cde");
    String string = list.get(0);
}

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryCast" />

UnnecessaryConstructor

不要なコンストラクタがないか
クラスにコンストラクタが1つで、デフォルトのコンストラクタと同じである場合

// NG
public class Sample {
    public Sample(){
    }
}

プロパティ

名前 デフォルト値 説明 複数指定
ignoredAnnotations javax.inject.Inject このルールで無視するアノテーションの完全修飾名 「|」区切り

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/UnnecessaryConstructor">
    <properties>
        <property name="ignoredAnnotations" value="javax.inject.Inject" />
    </properties>
</rule>

UnnecessaryFullyQualifiedName

import文を追加することで完全修飾名を使用しなくてよくなる箇所はないか

// NG
public class Sample {
    private java.util.List list; 
}

// OK
import java.util.List;
public class Sample {
    private List list; 
}

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName" />

UnnecessaryImport

使用していない不要なimport文はないか

// NG
import java.util.List;
import java.io.File; 
public class Sample {
    private List list; 
}

// OK
import java.util.List;
public class Sample {
    private List list; 
}

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryImport" />

UnnecessaryLocalBeforeReturn

returnする値を入れるだけの不要なローカル変数を生成していないか

// NG
public int execute() {
   int x = doSomething();
   return x;
}

// OK
public int execute() {
  return doSomething();
}

プロパティ

名前 デフォルト値 説明 複数指定
statementOrderMatters true falseの場合変数宣言とreturnが連続した行にある必要はなく、returnでのみ使用される変数は報告される -

ルール設定例

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

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

UnnecessaryModifier

不要な修飾子をつけていないか
インターフェースやアノテーション内のフィールドは自動的にpublic static finalとなり、メソッドはpublic abstractとなるので書く必要ない

// NG
public interface Animal {
    public abstract void doSomething();
}

// OK
public interface Animal {
    void doSomething();
}

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryModifier" />

UnnecessaryReturn

不要なreturnを書かない

// NG
public void doSomething() {
    int count = 3;
    return;
}

// OK
public void doSomething() {
    int count = 3;
}

ルール設定例

<rule ref="category/java/codestyle.xml/UnnecessaryReturn" />

UseDiamondOperator

ダイアモンド演算子を使用する

// NG
List<String> list = new ArrayList<String>();

// OK
List<String> list = new ArrayList<>();

プロパティ

名前 デフォルト値 説明 複数指定
java7Compatibility false java7で使用する場合trueにする -

ルール設定例

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

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

UselessParentheses

不要な括弧がないか

// NG
int count = (3);

// OK
int count = 3;

ルール設定例

<rule ref="category/java/codestyle.xml/UselessParentheses" />

UselessQualifiedThis

自分自身をさすときにクラス名から書かない

// NG
public class Sample {
    Sample sample = Sample.this;
}

// OK
public class Sample {
    Sample sample = this;
}

ルール設定例

<rule ref="category/java/codestyle.xml/UselessQualifiedThis" />

UseShortArrayInitializer

配列フィールドまたは変数を宣言および初期化する場合にnewを使用しない

// NG
int[] x = new int[] { 1, 2, 3 };

// OK
int[] x2 = { 1, 2, 3 };

ルール設定例

<rule ref="category/java/codestyle.xml/UseShortArrayInitializer" />

UseUnderscoresInNumericLiterals

桁数の多い数字の記述時にアンダースコアをつける
デフォルトでは5桁以上で3桁ごとにアンダースコアをつける必要がある

// NG
int number = 10000;

// OK
int number = 10_000;

プロパティ

名前 デフォルト値 説明 複数指定
acceptableDecimalLength 4 10進数の数値にアンダースコアが必要ない桁数 -

ルール設定例

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

<!-- プロパティ設定あり -->
<rule ref="category/java/codestyle.xml/AtLeastOneConstructor">
    <properties>
        <property name="ignoredAnnotations" value="lombok.Data|lombok.Value|lombok.Builder|lombok.NoArgsConstructor|lombok.RequiredArgsConstructor|lombok.AllArgsConstructor" />
    </properties>
</rule>

△VariableNamingConventions

非推奨のため省略


△WhileLoopsMustUseBraces

非推奨のため省略


他のカテゴリについてもまとめています。

Best Practiceカテゴリのまとめはこちら: 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