Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a name for the difference of these two code styles?

Tags:

java

When i see code from others, i mainly see two types of method-styling.

One looks like this, having many nested ifs:

void doSomething(Thing thing) {
  if (thing.hasOwner()) {
    Entity owner = thing.getOwner();
    if (owner instanceof Human) {
      Human humanOwner = (Human) owner;
      if (humanOwner.getAge() > 20) {
        //...
      }
    }
  }
}

And the other style, looks like this:

void doSomething(Thing thing) {
  if (!thing.hasOwner()) {
    return;
  }
  Entity owner = thing.getOwner();
  if (!(owner instanceof Human)) {
    return;
  }
  Human humanOwner = (Human) owner;
  if (humanOwner.getAge() <= 20) {
    return;
  }
  //...
}

My question is, are there names for these two code styles? And if, what are they called.

like image 428
0xLuca Avatar asked Jan 21 '21 06:01

0xLuca


1 Answers

The early-returns in the second example are known as guard clauses.

Prior to the actual thing the method is going to do, some preconditions are checked, and if they fail, the method immediately returns. It is a kind of fail-fast mechanism.

There's a lot of debate around those return statements. Some think that it's bad to have multiple return statements within a method. Others think that it avoids wrapping your code in a bunch of if statements, like in the first example.

My own humble option is in line with this post: minimize the number of returns, but use them if they enhance readability.

Related:

  • Should a function have only one return statement?
  • Better Java syntax: return early or late?
  • Guard clauses may be all you need
like image 161
MC Emperor Avatar answered Sep 20 '22 15:09

MC Emperor