Make the most of Pmd, Findbugs and CheckStyle result

Many Java static analysis tools exist right there, each one focus on a specific area and has its advantages, we can enumerate:
Pmd which is a static rule-set based Java source code analyzer that identifies potential problems like:
1. Possible bugs—Empty try/catch/finally/switch blocks.
2. Dead code—Unused local variables, parameters and private methods.
3. Empty if/while statements.
4. Overcomplicated expressions—Unnecessary if statements, for loops that could be while loops.
5. Suboptimal code—Wasteful String/StringBuffer usage.

FindBugs which looks for bugs in Java code. It uses static analysis to identify hundreds of different potential types of errors in Java programs.

Checkstyle defines a set of available modules, each of which provides rules checking with a configurable level of strictness (mandatory, optional…). Each rule can raise notifications, warnings, and errors.

Many ways exist to exploit the results of these tools:

XML format: XML files could be generated from each of these tools, and it can be used to create an HTML report or used by another tool to exploit the analysis result.
HTML format: HTML report is the prefered way to generate reports and share them between the team, and you can create your custom report by using an xsl stylesheet.
IDE Plugins: almost all known IDE provides plugins for these tools, which gives the possibility to discover all violations from the source code.

One of the problems with code quality tools is that they tend to overwhelm developers with problems that aren’t really problems — that is, false positives. When false positives occur, developers learn to ignore the output of the tool or abandon it altogether.
And to exploit better their result, it’s better to have a way to focus only on what we want and gives to developers a useful view. In this post we will discover another interesting way to exploit better the result of all known java static analysis tools, and query them like a database.

JArchitect and CQLinq –

JArchitect is another static analysis tool which complements the other tools, it uses a code query langage based on Linq ( CQLinq) to query the code base like a database.
Until JArchitect 3 you can query only analysis data extracted from JArchitect, however the V4 gives the possibility to import the analysis result from many other static analysis tools and query them with CQLinq.
Let’s take as example the source code of the PDT core (the Php plugin for eclipse). and discover how we can exploit the analysis result of these tools from JArchitect.
To begin here are the steps to follows before requesting the analysis result:
Step1:
Analyse the project with PMD, CPD, FindBugs and CheckStyle. And generate the XML files containing the result.
Step2:
Analyze the project with JArchitect.
Step3:
Import all the xml files into JArchitect from the menu “Plugins->Import Plugins Result Files”
JArchitect provides by default many useful queries to request these tools, and all these queries could be customized easily.

Let’s discover some CQLinq queries:

Get all issues:
The request to get all issues is very simple, however as you can see it’s not very interesting, indeed it’s a challenge to exploit a result with 232 725 issues.

To exploit better the result of these tools we can filter it with CQLinq and focus only on what we want.
Request by tool
We can modify the first request and add a criteria about the tool concerned.

Request by ruleset
We can also filter by issue ruleset :

Request by priority
We can also filter by priority:

Most recurrent issues
It’s interesting to know which issues are the most reported by these tools.


Classes having most issues
It’s very interesting to know the classes which contains many violations


As we can observe CheckStyle report thousand of issues and many of them could be ignored.
The previous query is interesting, but it’s not give us exactly the classes with lack of quality, another useful metric to take into account is the NBLinesOfCode, it’s normal that a class with many lines of code contains many issues, for that we can modify the previous request to calculate the ratio between the Issues count and the NBLinesofCode.


What’s very strange in this result is that the ratio of the 8 first classes is more than 200, in this case we have more than 200 issues by code line.
To explain this behavior let’s take a look at some lines of the CompilerAstParser:

The NbLinesOfCode is the number of statements and not the physical lines, and this Class declare many arrays , each one is declared by thousand of physical lines, however each array declaration is considered as one statement.
And as shown before for the most recurrent issues query, the following rule ‘+’ should be on a new line. is violated thousand of times for each array. Maybe it’s better to remove these kind of rules from the CheckStyle configuration file.

Most popular methods having issues

When the static analysis tools report the issues, it’s useful to locate which the prioritary issues to resolve? specially if it concerns bugs.
It’s true that a bug could exist in a specific method, but what interesting to know is how many methods are impacted by the bug, and the popular method are the most used ones and it’s better to resolve them quickly.

Using CQLinq we can combine the result of all these tools and also the result of JArchitect to create more elaborated queries, and add these checks to the build process.

Issues Trend
Having issues in a project is not an exception, we can say that’s normal, however we have to check the quality trend of the project. Indeed it’s a bad indicator if the number of issues grows after changes and evolutions.
JArchitect provides the Trend Monitoring feature to create trend charts. Trend charts are made of trend metrics values logged over time at analysis time. More than 50 trend metrics are available per default and it is easy to create your own trend metrics.
Let’s create a trend metric for the Pmd issues:

And after you can easily create the trend chart to monitor the previous trend metric and add it to the JArchitect dashboard.

With this trend chart we can monitor the evolution of the Pmd issues, and try to understand the reasons when the metric grows over versions.

Customize the JArchitect report
JArchitect make possible to append extra report sections in the HTML report that lists some CQLinq queries.
In the CQLinq Query Explorer panel, a particular CQLinq group reported is bordered with an orange rectangle.

You can also add to the report the Pmd trend chart:

And in the HTML report these added sections are accesible from the menu:

And here’s the page added in the report for the Pmd CQLinq queries:

Conclusion

JArchitect 4 is now open to other static analysis tools, and you can also plug your customized tool easily as descibed here. This way you can use all the JArchitect features to exploit better the result from the known java static analysis tools.

Learn Hibernate core implementation.- How hibernate works

Lessons to learn from the Hibernate Core implementation

Hibernate is an open source Java persistence framework project. Perform powerful object relational mapping and query databases using HQL and SQL.
In general the widely used libraries are well designed and implemented, and it’s very interesting to learn from them some coding best practices. Let’s take a look inside the hibernate core library and discover some of its design keys.
In this post Hibernate Core is analyzed by JArchitect to go deep inside its design and implementation.

Package by Feature
Package-by-feature uses packages to reflect the feature set. It places all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other.
Here’s a good article talking about packaging by feature.
Hibernate core contains many packages, each one is related to a specific feature hql, sql, and others.

Coupling
Low coupling is desirable because a change in one area of an application will require fewer changes throughout the entire application. In the long run, this could alleviate a lot of time, effort, and cost associated with modifying and adding new features to an application.
Here are three key benefits derived from using interfaces:
• An interface provides a way to define a contract that promotes reuse. If an object implements an interface then that object is to conform to a standard. An object that uses another object is called a consumer. An interface is a contract between an object and its consumer.
• An interface also provides a level of abstraction that makes programs easier to understand. Interfaces allow developers to start talking about the general way that code behaves without having to get in to a lot of detailed specifics.
• An interface enforce low coupling between components, what’s make easy to protect the interface consumer from any implementation changes in the classes implementing the interfaces.
Let’s search for all interfaces defined by Hibernate Core, for that we use CQLinq to query the code base.

from  t in Types where t.IsInterface select t

If our primary goal is to enforce low coupling, there’s a common mistake when using interfaces that could kill the utility of using them. It’s the using of the concrete classes instead of interfaces, and to explain better this problem let’s take the following example:
The class A implements the Interface IA who contains the calculate() method, the consumer class C is implemented like that

public class C

{

   ….

   public void calculate()

   {

     …..

     m_a.calculate();

     ….

    }

    A m_a;

}

The Class C instead of referencing the interface IA, it references the class A, in this case we lose the low coupling benefit, and this implementation has two major drawbacks:
• If we decide to use another implementation of IA, we must change the code of C class.
• If some methods are added to A not existing in IA, and C use them, we also lose the contract benefit of using interfaces.
C# introduced the explicit interface implementation capability to the language to ensure that a method from the IA will be never called from a reference to concrete classes, but only from a reference to the interface. This technique is very useful to protect developers from losing the benefit of using interfaces.
With JArchitect we can check this kind of mistakes using CQLinq, the idea is to search for all methods from concrete classes used directly by other methods.

from m in Methods  where m.NbMethodsCallingMe>0 && m.ParentType.IsClass

 && !m.ParentType.IsThirdParty && !m.ParentType.IsAbstract

let interfaces= m.ParentType.InterfacesImplemented

from i in interfaces where i.Methods.Where(a=>a.Name==m.Name &&

a.ParentType!=m.ParentType).Count()>0 

select new { m,m.ParentType,i }

For example the method getEntityPersister from SessionFactoryImpl which implements SessionFactoryImplementor interface is concerned by this problem.
Let’s search for methods invoking directly SessionFactoryImpl.getEntityPersister.
from m in Methods where m.IsUsing (“org.hibernate.internal.SessionFactoryImpl.getEntityPersister(String)”)
select new { m, m.NbBCInstructions }

Methods like SessionImpl.instantiate invoke directly getEntityPersister, instead of passing by interface, what break the benefit of using interfaces. Fortunately hibernate core doesn’t contains many methods having this problem.
Coupling with external jars
When external libs are used, it’s better to check if we can easily change a third party lib by another one without impacting the whole application, there are many reasons that can encourage us to change a third party lib. The other lib could:
– Have more features.
– More powerful.
– More secure.
Let’s take the example of antlr lib which used to parse the hql queries, and imagine that another parser more powerful than antlr was created, could we change the antlr by the new parser easily?
To answer this question let’s search which methods from hibernate use it directly:

from m in Methods where m.IsUsing ("antlr-2.7.7")
select new { m, m.NbBCInstructions }
 

And which ones used it indirectly:

from m in Projects.WithNameNotIn( "antlr-2.7.7").ChildMethods()
let depth0 = m.DepthOfIsUsing("antlr-2.7.7")
where depth0 > 1 orderby depth0
select new { m, depth0 }

Many methods use antlr directly what makes hibernate core highly coupled with it, and changing antlr with another one is not an easy task. this fact not means that we have a problem in hibernate design, but we have to be careful when using a third party lib and well check if a third party lib must be low coupled or not with the application.
Cohesion
The single responsibility principle states that a class should have one, and only one, reason to change. Such a class is said to be cohesive. A high LCOM value generally pinpoints a poorly cohesive class. There are several LCOM metrics. The LCOM takes its values in the range [0-1]. The LCOMHS (HS stands for Henderson-Sellers) takes its values in the range [0-2]. Note that the LCOMHS metric is often considered as more efficient to detect non-cohesive types.
LCOMHS value higher than 1 should be considered alarming.
In general classes more concerned by the cohesion are the classes having many methods and fields.
Let’s search for types having many methods and fields.

from t in Types where
(t.Methods.Count() > 40 || t.Fields.Count()>40) && t.IsClass
orderby t.Methods.Count() descending
select new { t, t.InstanceMethods, t.Fields,t.LCOMHS }

Only few types are concerned by this query, and for all them the LCOMHS is less than 1.
Using Annotations
Annotation-based development relieves Java developers from the pain of cumbersome configuration. And give us a powerful feature to free the source code from the boilerplate code. The resulting code is also less likely to contain bugs.
Let’s search for all annotations defined by hibernate core.
from t in Types where t.IsAnnotationClass && !t.IsThirdParty select t

Many annotations are defined, what make hibernate easy to use by developers, and the headache of configuration files is avoided.
Conclusion
Hibernate Core is a good example of open source projects to learn from, don’t hesitate to take a look inside it.