JoeG
JoeG

Reputation: 7652

Findbugs, PMD or Checkstyle rule to find access by a field

I have a class caches a set of values internally. These values can be updated periodically and the cached contents will be updated appropriately. As long as users of this class do something like:

...
public void anyMethod(anyParams) {
    AnyObject value = CacheClass.getValue(anyKey);
    ...
}

Then life will be fine as that "value" will not maintained locally. However if anyone does something like this:

public class MyClass {
    private AnyObject value = CacheClass.getValue(someKey);
   ...
}

Then if the cached value is updated the usage of it may not see the new value.

We use findbugs, checkstyle and PMD in the builds via Sonar. So I am wondering if there is a way to define a rule in any of these systems to detect and flag the second type of usage above. I have never written a rule in any these systems so would appreciate as much advice as possible (like, "well it can be done, but you really don't want to go there..." :)

Upvotes: 2

Views: 244

Answers (1)

R Kaja Mohideen
R Kaja Mohideen

Reputation: 917

Following XPath on your AST Node will catch Field declarations that calls your CacheClass method.

//FieldDeclaration[//PrimaryExpression/PrimaryPrefix/Name/@Image='CacheClass.getValue']

How to write PMD Custom Rule

Upvotes: 5

Related Questions