Java – if and else or if and return

cyclomatic-complexityjava

I have a Java method with a void type of return that checks a condition. It do something in case of true and other thing in case of false, typical if / else structure, but is possible use only the if block with a empty return in the end and omit the else block placing its contents with one less level of indentation. I don't know the implications of use one or other form, is one of they a bad practice? or use one or the other is a personal election?

// The first way
private void test(String str) {
    if (str.equals("xxx")) {
        // Do something
    } else {
        // Do other thing
    }
}

// The second way
private void test(String str) {
    if (str.equals("xxx")) {
        // Do something
        return;
    }
    // Do other thing
}

Best Answer

It depends on the semantics of your code, if the else branch is the point of the method, i.e. it's named after what happens in the else branch, the early return is probably correct, especially if the first part is some sort of check.

If on the other hand the two branches are both related to the methods functionality, the if/else makes more sense to use.

ex.

void frob(...)
{
   if(isBlob())
      return; //can't frob a blob
   doFrobbing(...)
}

vs.

void condOp(...)
{
  if(condition)
      conditionalthing();
  else
      otherthing();
}

making the code match the semantics of your method makes it easier to read.