Why java method name should not contain underscore? - java

I am using PMD for checking java coding violation.
I am writing automation test cases, and given method name like this:
public void testCaseMethod_4_2_16(){
//some implementation
}
where 4_2_16 is test case number 4.2.16
and when I check for PMD violation it is showing method name should not contain underscore, and this violation is shown as blocker according to PMD rules.
So here are my question:
Why method name should not contain underscore is define as a blocker or PMD error?
What kind of PMD violation we should avoid and
What kind of violation we should try to fixed?
As for my understanding at least we should avoid first two level of violation shown by PMD.
Any help on the PMD rule will be appreciated. thanks

It is a standard that has been set so that people can easily read each other's code, therefore making code more maintainable.
The quote below is from Oracle's website on Java code conventions:
80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

Java prefers camelCase notation. Java code conventions say that you should try to avoid underscores in method or variable name whenever it is possible.
In your case PMD's default prioritization fails. This rule should be on a "nice-to-have" level, but definitely not a blocker issue.
I would recommend you to use SonarQube, which did a re-prioritization of PMD's rules, which works better is most cases. The rule you found is just on Major level (below levels Blocker and Critical).
If you are still not satisfied with the results, you can use the SourceMeter plugin for SonarQube, which has a different (possible better) prioritization of PMD rules as well.

Although there are lots of opinions out there, I like to separate quality-assurance for production and the one for test code.
If that is not possible for whatever reason, I'd rather deactivate (most of) the warnings for test-code. I think it is not worth the time making the test-code pretty (and underscores in method names is just styling to me), while there are serious warnings for the production code left open.

In java underscore is allowed while naming identifiers. I don't know why PMD is showing violation but you can just deactivate the warnings and go on. UNDERSCORE is allowed in java while naming identifiers.
I think it may help you...

Related

Sonar rule for interfaces only RSPEC-1213

I want to modify / make the rule target only public interfaces (not public classes etc). Is this possible ? Im using this rule in Java code but its too strict for my project and I would love to know if there is a way to change it a little bit.
Link for rule: https://rules.sonarsource.com/java/RSPEC-1213
For an existing ruleset on SonarQube, talk to your sonar administrator to change the rules that are enforced on the code and remove that particular one from global enforcement.
There have been a few times I've gone to the admins of the tool for the install that I use and said "this rule isn't one that I care about or will enforce and only makes it confusing" and had them remove that rule from the globally run ruleset.
Is it possible to write your own rule?
Yes, it is possible. From SonarQube's docs: Adding coding rules you have some options. Either you can write a plugin for SonarQube and add that to your instance (docs), or you can write an external application that analyzes the code which SonarQube consumes.
If you don't have your own instance of sonarqube or aren't up to writing the associated plugin or external tooling... you might want to instead lookout PMD (site).
For PMD, writing a custom rule can be much simpler (docs). One of the ways that PMD works is by 'compiling' the Java code into an XML representation of the abstract syntax tree for Java and then running xpath queries against that XML (tutorial).
The xpath rule can then be included in a project's configuration.
What about turning it off for the code that I'm working on?
If a specific rule is one that you don't want to invoke, you could suppress it with #SuppressWarnings("java:S106") (that particular spares warnings is for System.out.println use, but the same structure can be used for other warnings) or by adding // NOSONAR too strict on the line. There are spots where I have such comments where following the rule for a particular set of code is problematic and suppress it for that line, method, or class - with the comment about why that is done.
That particular rule... I'm gonna agree with the Java (and now Oracle) guidelines and follow it. The reason is that if anyone else works on the code, they'll expect it to follow that convention. Having a consistent understanding of what things should be where in code so that another developer doesn't need to go dig through an entire file to find the constructor when it is expected to be at the top (under the field definition) is a good thing. What's more, it limits the future cases where a developer goes through to make things consistent with conventions and results in a lot of style: updating code to follow style guide commits later.

Is there a Java tool to reduce the visibility of methods

I have a legacy code base that I want to refactor to reduce the visibility of methods to the minimum possible (private, protected, default) such that the code still works. Many of the methods in the codebase are unnecessarily public, and I'd like to change that to reduce the interface burden and simplify documentation as the code evolves in the future. Is there a tool that will analyze the codebase and generate a list of suggested methods whose visibility can be reduced? I can specify all the entry points into the code (just the main methods), and the codebase doesn't use reflection.
An Eclipse plugin will be even better.
Take a look at UCDetector (Unnecessary Code Detector - pronounced "You See Detector")
http://www.ucdetector.org/
It is an eclipse plugin and it helps to reduce visibility. I have used it for long time and it works very well.
Although there are tools that you can use to report the occurrence of methods which visibility can be reduced, I am not aware of something that allows you to transform the code to solve those issues.
However, you may find interesting taking a look to JTransformer and Ekeko.
Both allows you to query and accomplish custom code transformations based on logic programming techniques. JTransformer may be a bit more mature, but Ekeko also looks quite interesting. To the best of my knowledge they both are open source and include an Eclipse plugin.

Tool to identify cohesive blocks of (JAVA) code

I am wondering if there is a tool that can identify cohesive blocks of code within JAVA source code.
For example if I had a long method that I would like to extract another method from - is there any tool that automatically can tell me large chunks of code that would be worth extracting?
There are plug-ins like PMD (for eclipse) & FindBugs etc., to do static code review which flags code based on rules your configured.
Google CodePro Analytics has an Eclipse plug-in that can provide a bunch of statistics like lines of code and cyclomatic complexity that can be good indicators that a method should be refactored.
I don't think you will find a tool that can automatically refactor 'cohesive' blocks of code into methods. There is too much subjectivity in that.
I looked for a similar tool with another question: https://stackoverflow.com/questions/12016289/tool-for-visualizing-dependencies-inside-a-java-class just on a slightly higher level: a single class.
I think the same answer applies: There isn't anything like that. There are tools though that provide information from which you might extract the information you are looking for.
I'd look into DependencyFinder. It provides access to all the bits and pieces of the code, so you could find clusters of code elements that access a common set of variables. Unfortunately I found the API a little confusing and not well documented, so you'll need some try and error or get into contact with the author. It also probably won't give you access to whitespace I think. But I don't think this is a valid approach anyway.
Another Tool you might want to look into is JaMoPP It should even have information about whitespace. Although it is a Java Plugin you can use the underlying library independent of eclipse (I think).
Check out Sonar It has very good support for finding duplicate code blocks.
Sonar uses PMD and FindBugs underlying. It also generates some custom metrics like class complexity, method complexity which points to classes / methods that are too large and which are candidate for breaking down.
Control blocks (i.e. conditionals and loops) are "cohesive" in that you cannot readily extract blocks of code that cross control block boundaries. Find blocks that can be replaced by a method call, that makes the original method easier to understand. You will have the best impact on complexity by extracting out the regions of deepest control flow nesting, so this is a good place to start. You don't need a tool as such - the code itself has the info you need.

Checkstyle vs. PMD

We are introducing static analysis tools into the build system for our Java product. We are using Maven2 so Checkstyle and PMD integration come for free. However it looks like there is a large overlap in functionality between these two tools, in terms of enforcing basic style rules.
Is there a benefit from utilizing both of these? I don't want to maintain 2 tools if one will work. If we choose one, which one should we use and why?
We are also planning on using FindBugs. Are there other static analysis tools we should look at?
Update: Consensus seems to be that PMD is preferred over CheckStyle. I don't see a solid reason to use both, and I don't want to maintain 2 sets of rule files, so we will probably aim for PMD exclusively. We'll also be bringing in FindBugs, and perhaps, eventually, Macker to enforce architectural rules.
You should definitely use FindBugs. In my experience, the false-positive rate is very low, and even the least-critical warnings it reports are worth addressing to some extent.
As for Checkstyle vs. PMD, I would not use Checkstyle since it is pretty much only concerned with style. In my experience, Checkstyle will report on a ton of things that are completely irrelevant. PMD on the other hand is also able to point out questionable coding practices and its output is generally more relevant and useful.
Both softwares are useful. Checkstyle will help you during your programming by checking your coding style i.e braces, naming etc. Simple things but very numerous!
PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the clone function. Simply, PMD will check your programming style
However, both softwares suffers from similar rules sometimes bad explained. With a bad configuration, you may check things twice or two opposite things i.e "Remove useless constructors" and "Always one constructor".
If we choose one, which one should we use and why?
These tools are not competing but are complementary and should be used simultaneously.
The convention type (Checkstyle) is the glue that enables people to work together and to free up their creativity instead of spending time and energy at understanding inconsistent code.
Checkstyle examples:
Is there javadoc on public methods ?
Is the project following Sun naming conventions ?
Is the code written with a consistent format ?
while PMD reminds you bad practices:
Catching an exception without doing anything
Having dead code
Too many complex methods
Direct use of implementations instead of interfaces
Implementing the hashcode() method without the not equals(Object object) method
source:
http://www.sonarsource.org/what-makes-checkstyle-pmd-findbugs-and-macker-complementary/
We use both:
Checkstyle to make sure that everyone in the team write code in a similar maner
PMD to find problematic code areas and next refactoring targets
If your primary place of use is while developing in eclipse, then CodePro from Instantiations will be best. Earlier it was a commercial tool, but now Google bought Instantiations so CodePro analytix is free now.
Check out http://code.google.com/javadevtools/download-codepro.html
If you reviewed Checkstyle, PMD and Findbugs rule lists, you have seen that all three provide valuable output and all three overlap to a degree and also bring their own, unique rules to the table. This is why tools like Sonar use all three.
That said, Findbugs has the most specific or niche rules (e.g. "Dubious catching of IllegalMonitorStateException" - how often are you likely to run into that?) so it is usable with little or no configuration and its warnings should be taken seriously. With Checkstyle and PMD the rules are more general and style-related so they should only be used with custom configuration files to spare the team from an avalanche of irrelevant feedback ("Tab char on line 5", "Tab char on line 6", "Tab char on line 7"... you get the picture). They also provide powerful tools to write your own advanced rules, e.g. the Checkstyle DescendentToken rule.
When using all three (especially with a tool like Sonar), all of them should be configured separately (takes at least a few days to cover all the rules) while paying attention to prevent duplication (all three tools detect that hashCode() has been overridden and equals() not, for example).
In summary, if you consider static code analysis valuable, rejecting the value any of the three provides makes no sense, but to use all three, you have to invest time to configure them to give you usable feedback.
Sonar (http://www.sonarsource.org/) is a very useful open platform to manage code quality, and includes Checkstyle, PMD, Findbugs and much more.
This also indicates that all 3 tools have their right to exist...
Both tools are configurable and can do just about the same things. That said, if we're talking about out-of-the-box stuff, there is a great deal of overlap, but there are distinct rules/checks as well. For example, Checkstyle has stronger support for checking Javadoc and finding magic numbers, to name a couple. Additionally, Checkstyle has an "import control" feature that looks similar to the functionality of Macker (I've not used Macker).
If there are things that are important to you that Checkstyle does out-of-the-box that PMD doesn't, you might consider a minimal Checkstyle configuration with only those checks. Then institute a policy that the Checkstyle configuration cannot grow, simply remove checks as you implement similar functionality with, say, custom PMD rules.
Also consider that if you decide that the Checkstyle "import control" feature covers what you wanted from Macker, then you could implement PMD/Checkstyle instead of PMD/Macker. Either way it's two tools, but with Checkstyle, you'd get the stuff that PMD doesn't do out-of-the-box "for free."
Checkstyle and PMD both are good at checking coding standards and are easy to extend.
But PMD has additional rules to check for cyclomatic complexity,Npath complexity,etc which allows you write healthy code.
Another advantage of using PMD is CPD (Copy/Paste Detector).It finds out code duplication across projects and is not constrained to JAVA.It works for JSP too.
Neal Ford has a good presentation on Metrics Driven Agile Development, which talks about many tools that are helpful for Java/Java EE Development
I find Checkstyle and PMD are best for enforcing style issues and simple obvious coding bugs. Although I've found that I like using Eclipse and all the warnings it provides better for that purpose. We enforce stuff by using shared preferences and marking them as actual errors. That way, they never get checked in in the first place.
What I would strongly and enthusiastically recommend is using FindBugs. Because it works at the bytecode level it can check things that are impossible at the source level. While it spits out its fair share of junks, it has found many actual and important bugs in our code.
And 10 years later ...
In 2018 I use all of them Checkstyle, PMD and FindBugs.
Start with FindBugs. Maybe add PMD and Checkstyle later.
Never blindly enforce the default rules !
Steps:
run one tool with default rules on a project which has a lot of code
adapt the rules to this project, comment out useless rules with some notes
focus on the low hanging fruits rules (NPE, logger checks, unclosed resource checks, ...)
perform some fixes for rules you find worthwhile (one at a time !)
do this for each tool but not all at once !
repeat this process
Ideally each project can have separate rules.
I like running the rules via the build (via maven plugins) and fail on rule errors once I know a project passes all the rules I defined.
This forces developers to take action, because reporting is not enough.
From that point on your project is pretty much bullet proof and you could even add more rules later on and/or write custom rules.
One point I have not seen so far is that there are plugins for IDEs that will enforce CheckStyle rulesets on your code, whereas PMD plugins will only report on violations. For example, in a multi-site project over several programming teams, it's important to actively enforce standards, rather than just to report on them.
Both tools have plugins available for IntelliJ, NetBeans, and Eclipse (in my view this covers most usage). I'm not as familiar with NetBeans, so can only comment on IntelliJ and Eclipse.
Anyway, the PMD plugins for IntelliJ, and Eclipse, will generate reports on demand on PMD violations within the project codebase.
The CheckStyle plugins, on the other hand, will highlight violations on the fly, and can (at least for IntelliJ, I have less experience with Eclipse) be configured to automatically convert some issues (e.g. for 'OneStatementPerLine', will place CR-LF between statements, for 'NeedBraces', will add braces where they are missing, etc.). Obviously, only the simpler violations can be automatically fixed, but it's still a help on legacy projects, or projects located over several locations.
'On demand' for PMD means that the developer must consciously decide to run the report. Whereas Checkstyle violations are automatically reported to them as they develop. While PMD does contain a more extensive ruleset, in my mind the automatic enforecement/reporting of violations in IDEs is worth the hassle of maintaining 2 sets of rules.
So for any projects I work on, we use both tools, Checkstyle enforced in the IDE, PMD reported in the IDE, and both reported and measured in builds (through Jenkins).
Take a look at qulice-maven-plugin that combines together Checkstyle, PMD, FindBugs and a few other static analyzers, and pre-configures them. The beauty of this combination is that you don't need to configure them individually in every project:
<plugin>
<groupId>com.qulice</groupId>
<artifactId>qulice-maven-plugin</artifactId>
<version>0.15</version>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
I would echo the comment that PMD is the more current product for Java style/convention checking. With respect to FindBugs, many commercial development groups are using Coverity.
PMD is what I find more people referring to. Checkstyle was what people were referring to 4 years ago but I believe PMD is maintained more continuously and what other IDEs/plugins choose to work with.
I have just started to use Checkstyle and PMD. To me, PMD is more easier to create customized rules for things such that whether there exists System.gc(), Runtime.gc(), as long as you can write the XPath Query which is also not difficult at all. However, PMD has not shown me that it has the feature to show column number. So for things like check column limits. You might would like to use Checkstyle.
PMD is the finest tool when compare with checkstyles. Checkstyles may not have the capability to analyse the code while PMD offering many features to do so! Offcourse PMD has not released rules for javadoc, comments, indentations and etc. And by the way i am planning to implement these rules.......thanx

Cross-class-capable extendable static analysis tool for java?

I'm trying to write rules for detecting some errors in annotated multi-threaded java programs. As a toy example, I'd like to detect if any method annotated with #ThreadSafe calls a method without such an annotation, without synchronization. I'm looking for a tool that would allow me to write such a test.
I've looked at source analyzers, like CheckStyle and PMD, and they don't really have cross-class analysis capabilities. Bytecode analysers, like FindBugs and JLint seem rather difficult to extend.
I'd settle for a solution to something even simpler, but posing the same difficulty: writing a custom rule that checks whether each overriden method is annotated with #Override.
Have you tried FindBugs? It actually supports a set of annotations for thread safety (the same as those used in Java Concurrency in Practice). Also, you can write your own custom rules. I'm not sure whether you can do cross-class analysis, but I believe so.
Peter Ventjeer has a concurrency checking tool (that uses ASM) to detect stuff like this. I'm not sure if he's released it publicly but he might able to help you.
And I believe Coverity's static/dynamic analysis tools for thread safety do checking like this.
You can do cross-class analysis in PMD (though I've never used it for this specific purpose). I think it's possible using this visitor pattern that they document, though I'll leave the specifics to you.
A simple tool to checkup on annotations is apt (http://java.sun.com/j2se/1.5.0/docs/guide/apt/ also part of Java 6 api in javax.annotation.processing) however this only has type information (ie I couldn't find a quick way to get at the inheritance hierarchy using the javax.lang.model api, however if you can load the class you can get that information using reflection).
Try javap + regexes (eg. Perl)

Categories