Single line braces in checkstyle gives error - java

I want Checkstyle in Java to not give me any errors for the following line of code -
if (true) { return 1; }
But it gives me errors, '}' should have line break before. and '{' should have line break after. My LeftCurly block is as follows:
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
My RightCurly is as follows:
<module name="RightCurly">
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
My NeedBraces is as follows:
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, LITERAL_IF, LITERAL_ELSE"/>
</module>
How do I allow single line blocks to have opening and closing braces on the same line? Thanks!
I'm using the Gradle Checkstyle plugin, Checkstyle version: 6.7

Your right curly option "same" means something different:
The brace should be on the same line as the next part of a multi-block statement
So for your case you should use the option alone_or_singleline:
<property name="option" value="alone_or_singleline"/>
See rcurly for more.
Also it is always a good idea to think about a consistent code style which avoids having exceptions! So think about another developer that will insert code some month later into your block - would be easier when the block is not on the same line.

Related

Why are java interface constants treated as non-public by ConstantName check in Checkstyle

In our project we want to ensure that the private constants always start with _ (underscore) and rest all do not start with an underscore.
The checkstyle check ConstantName fails to treat the interface constants as public and applies the rules of private modifier.
We are using checkstyle 8.35 in our gradle project to analyse java code (OpenJdk 11, Gradle 6.4).
Below is the code snippet of Interface with constants.
public interface MyInterface() {
int MAX_SIZE = 1024;
//Some methods here
}
Checkstyle configuration for ConstantName check is as below
<module name="ConstantName">
<property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
<property name="applyToPrivate" value="false"/>
</module>
<module name="ConstantName">
<property name="format" value="^_[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
<property name="applyToPublic" value="false"/>
<property name="applyToProtected" value="false"/>
<property name="applyToPackage" value="false"/>
</module>
Post running the checkstyle analysis the error is reported for MAX_SIZE as Name 'MAX_SIZE' must match pattern '^_[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'. while our expectation is No Errors.
Judging by a quick scan of the source code, this is a bug. They're only considering the constant to be public if the keyword public is present (which is the case in classes, but not interfaces).
I would suggest reporting this as an issue at https://github.com/checkstyle/checkstyle/issues

How can I limit an annotation 's target only to be 'ElementType.TYPE_USE',

How can I limit an annotation 's target only to be 'ElementType.TYPE_USE', and any other use would be rejected by 'maven checkstyle' plugin
I could only think of RegexpMultiline, if you want to do it with Checkstyle. You might configure it like so (regex):
<module name="RegexpMultiline">
<property name="format" value="\bElementType\s*\.\s*(?!TYPE_USE)\w+\b"/>
<property name="message" value="Illegal ElementType. Only TYPE_USE is permitted."/>
<property name="fileExtensions" value="java"/>
</module>
This solution is far from perfect, as it will also trigger on comments, and is not limited to annotations. Write a custom check if you need more control.

Checkstyle check RegexpHeader: Does not allow me to assign a regex to the value of its property header

I a using RegexpHeader check from Checkstyle. I have a property header whose value I have set to
^(.|\n)*#.*ParamsAreNonNull$ .
The checkstyle throws an error:
cannot initialize module RegexpHeader - Cannot set property 'header' to '^(.|\n)*#.*ParamsAreNonNull$' in module RegexpHeader'
What could be the reason? This regex works perfectly on regex101.com and is the one that I want.
I changed the check to Regexp since the above check is only for single line apparently.
<module name="Regexp">
<property name="format" value="^(.|\n)*#.*ParamsAreNonNull$"/>
<property name="message" value="Annotation Not Found"/>
<property name="ignoreComments" value="true"/>
<property name="severity" value="error"/>
</module>
Error:
java.util.regex.Pattern$Loop.match(Pattern.java:4785)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717)
at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777)
at java.util.regex.Pattern$Branch.match(Pattern.java:4604)

Checkstyle – ignore Javadoc while checking duplication

I am using checkstyle to check violation in my code. One of the module in my configuration is about duplicate code. Since I am using StrictDuplicateCode I get violation on duplication for javaDoc as well.
Can anyone guide me to achieve my goal?
In the meantime, I tried following BUT it doesn’t work:
To suppress duplication with java doc I created a separate xml file (JavaDocSup.xml) with following content
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress checks="JavadocStyleCheck"
files="SomeClass.java"
/>
</suppressions>
Then I added following code in my main configuration file. Following is the code for my config file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="severity" value="warning"/>
<module name="TreeWalker">
<module name="MethodLength">
<property name="max" value="50"/>
</module>
<module name="ParameterNumber">
<property name="max" value="4"/>
</module>
<module name="CyclomaticComplexity"/>
</module>
<module name="StrictDuplicateCode">
<property name="fileExtensions" value="java"/>
</module>
<module name="SuppressionFilter">
<property name="file" value="${samedir}/JavaDocSup.xml"/>
</module>
</module>
When I run the checkstyle on my code, it still detects the duplicate lines in the Java doc.
Is the suppress checks="JavadocStyleCheck” is correct?
Any help will be highly appreciated. Thanks.
Checkstyle's StrictDuplicateCode is found to be inefficient, hence it's thrown away (since Checkstyle 6.2). Try using other tools like PMD's CPD, etc.
If you want to stick to current Checkstyle version, you can try adding <property name="min" value="20"/> to throw the violation only if at least 20 lines are matching.
(Some clone detection tools are mentioned under Tools section in Wikipedia)

Checkstyle issuing an indentation warning on an annotation?

I have an annotation like:
#ComponentScan(
basePackages = {
"com.example.foo",
"com.example.bar"
} // <--- false positive reported in this line
)
public class FooBar extends WebMvcConfigurerAdapter {
...
}
And a Checkstyle configuration of:
<module name="AnnotationUseStyle" />
<module name="Indentation">
<property name="basicOffset" value="2" />
<property name="braceAdjustment" value="0" />
<property name="caseIndent" value="2" />
</module>
When I run my project through Checkstyle, I get an error stating "assign child at indentation level 2 not at correct indentation, 4". This is referencing line 5 of my code example above, i.e. the closing parenthetical for the basePackages property.
What configuration change to Checkstyle would I need to make for this annotation to validate correctly?
It's a known issue in checkstyle: github.com/checkstyle/checkstyle/issues/553
As a workaround you can set lineWrappingIndentation property to zero:
<module name="Indentation">
<property name="lineWrappingIndentation" value="0"/>
</module>
But in this case you will also need to remove extra indentations after line breaks, e.g.
return getCalculator().
calculate(...);
instead of
return getCalculator().
calculate(...);

Categories