GeezerVison is showing github.com — [java] New Rule InvalidJavaBean · Issue #4177 · pmd/pmd
[java] New Rule InvalidJavaBean #4177Description
Proposed Rule Name: InvalidJavaBean
Proposed Category: Design
Description:
This rule would provide the "bean" part of BeanMembersShouldSerialize.
It would check, that the analyzed class adheres to the Java Beans Specification, that means:
- Each field has a correctly named getter and setter
- for indexed properties, check the field is an array and the types match
- event listeners implement
java.util.EventListener
- event listeners always come in pairs (addXXListener, removeXXListener)
- the bean as a default no-arg constructor
- the bean is serializable (that means, it implements
java.io.Serializable- for the actually check, see the rule NonSerializableClass [java] Rename BeanMembersShouldSerialize to NonSerializableClass #4176)
Care must be taken to make this rule not as noisy as #1668 . One strategy could be:
- consider only classes, that have at least one getter or setter (that means, a method matching the naming conventions). These classes could be beans.
- consider imports: PropertyChangeListener, VetoableChangeListener, EventListener might give a hint, that the class under analysis might be a bean.
- maybe have a minimum number of properties - so that the rule is not triggered yet, when a class has only one getter?
- providing a property to configure a package or a naming convention for bean classes?
- Consider annotations in
java.beans
Related issues:
References:
Code Sample:
public class MyBean { // <-- bean is not serializable, missing "implements Serializable"
private String label; // <-- missing setter for property "label"
public String getLabel() {
return label;
}
}
Possible Properties:
package - a regex to configure the packages where this rule should be applied to
ensureSerialization - whether or not to check for java.io.Serializable
Activityjsotuyod commented on Oct 27, 2022 Some personal comments…
Firstly, I'd go for the approach of having to setup the rule with a required package to avoid the noisiness. The criteria for inference are too vague and would produce significant FPs / FNs.
I'd also have the check for serialization be optional through a property. Why? Because even though the actual usage of Java Beans as communication value objects has declined with JavaEE, the idea of an object with a default constructor with getters and setters has endured, and is used massively in other scenarios, such as:
- Bean Validation (JSR 303 / 380), used standalone but also supported by Jersey, Spring and plenty of others.
- JAXB
- Jackson JSON library (when no annotations present)
Being able to enforce the compliance of these would be useful, as an error is mostly silent, with properties being dropped… Reacted by Andreas Dangel
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|