Just return from the method already

06 Mar 2006

Got any code like this?

public boolean foo(int x) {
  if (x>2) {
    return true;
  } else {
    return false;
  }
}

My goodness! That's five lines of code to do something pretty basic. Run this thru PMD's SimplifyBooleanReturns and it'll suggest reducing this to:

public boolean foo(int x) {
  return x>2;
}

This is a fair bit easier to read - and as a bonus, you shave four bytes off the class file! Good times.

For more on this sort of thing, get the PMD book!