Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PMD rules confliction:A method should have only one exit point, and that should be the last statement in the method

Tags:

java

pmd

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:

enter image description here

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 :)

like image 535
soulmachine Avatar asked May 09 '12 09:05

soulmachine


2 Answers

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.

like image 194
Jon Skeet Avatar answered Sep 22 '22 17:09

Jon Skeet


Using

return (condition > 5) ? Integer.valueOf(123) : null;

But I don't know if that's "code smell" too... :)

like image 42
javatutorial Avatar answered Sep 21 '22 17:09

javatutorial