The "Why" behind PMD's rules

In each case, the rule can be a matter of specific circumstances or just "taste".

Instantiating an Object in a loop should be avoided if there are a large number of iterations and the instantiation is expensive. If you can move the code out of the loop, you will avoid many object instantiations, and therefore improve performance. Having said that, this isn't always possible, and in some cases it just doesn't matter to the overall performance of the code. In these cases, do whichever is clearer.

For OnlyOneReturn, there are several ways to view this (with vehement supporters behind each), but they all basically boil down to taste.

For your example, the OnlyOneReturn proponents want code like:

public int performAction(String input) {
    int result;
    if (input.equals("bob")) {
        result = 1;
    } else {
        result = 2;
    }
    return result;
}

Rather than:

public int performAction(String input) {
    if (input.equals("bob")) {
        return 1;
    } else {
        return 2;
    }
}

As you can see, the additional clarity of ReturnOnlyOnce can be debated.

Also see this SO question that relates to instantiation within loops.


This article, A Comparison of Bug Finding Tools for Java, "by Nick Rutar, Christian Almazan, and Jeff Foster, compares several bug checkers for Java..."—FindBugs Documents and Publications. PMD is seen to be rather more verbose.

Addendum: As the authors suggest,

"all of the tools choose different tradeoffs between generating false positives and false negatives."

In particular, AvoidInstantiatingObjectsInLoops may not be a bug at all if that is the intent. It's included to help Avoid creating unnecessary objects. Likewise OnlyOneReturn is suggestive in nature. Multiple returns represent a form of goto, sometimes considered harmful, but reasonably used to improve readability.

My pet peeve is people who mandate the use of such tools without understanding the notion of false positives.

As noted here, more recent versions of PMD support improved customization when integrated into the build process.