Java code PMD complains as Method should have only one exit point

public boolean validate(final Beanform[] bagdata) {
        final int length = bagdata.length;
        if (length == 4) {
            return true;
        } else if (length == 1) {
            result = "length==1, Length should be greater than 1";
            return false;
        } else if (length == 3) {
            if (bagdata[0].getCycleType() == null) {
            result = "Cyclic Type is null for length==3";
                return false;
            }
        }

        return true;
    }

Hi ,

The above is piece of java code , that is working fine . However when i ran the code aganist PMD . A method should have only one exit point, and that should be the last statement in the method

Could you anybody please tell me how to mould this code , so that it follows A method should have only one exit point, and that should be the last statement in the method And what is the best prtacie in this types of code ??

please share your experience on this .

Answer

Are you sure it didn’t say that your method should only have one exit point?

The code you’ve shown has only one entry point, but 4 exit points.


Update: we’re talking about exit points.

First, just because a tool tells you that it doesn’t like your working code doesn’t mean it’s right and you’re wrong. The single/multiple exit point debate has a long history; both are probably right to a certain extent. In other words, don’t fix what ain’t broke!

But if you do want to appease PMD, here’s what you could do:

  • declare a boolean variable, i.e. isValid, at the top of your method
  • replace every return true/false statement with isValid = true/false
  • at the end of the method, return isValid

Leave a Reply

Your email address will not be published. Required fields are marked *