sometimes I found that a few PMD rules conflict with each other, therefore you can not write code that satisfies all PMD rules.
For example, it seems the following two rules exclude with each other: "Assigning an Object to null is a code smell. Consider refactoring." and "A method should have only one exit point, and that should be the last statement in the method"
The following is my example code:
if I use get1(), I will violate the former rule, and if I use get2(), then I will violate the latter rule. I prefer that A method should have only one exit point, but I don't want PMD reports that "Assigning an Object to null is a code smell", does anybody have any good idea? Thanks a lot :)
In both of these cases, I'd use the conditional operator:
return condition > 5 ? Integer.valueof(123) : null;
Personally I don't try to stick to one exit point though. There are far too many times when that makes the code less readable - often you can tell at the start of the method what the return value should be (e.g. due to it being a base case)... so why not just return it? Code which dogmatically sticks to "only one exit point" typically ends up with unnecessarily nested code which is then harder to scour through.
Using
return (condition > 5) ? Integer.valueOf(123) : null;
But I don't know if that's "code smell" too... :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With